VUEX模块间如何进行相互调用
概要
Vuex 可以帮助我们管理共享状态,是否选择使用这需要对短期和长期效益进行权衡。如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。如果你的应用够简单,您最好不要使用 Vuex。一个简单的 store 模式就足够您所需了。但是,如果您需要构建一个中大型单页应用,您很可能会考虑如何更好地在组件外部管理状态,Vuex 将会成为自然而然的选择。
初始化vuex-demo
使用vue-cli 4.x创建vue项目,选择test选项初始化项目,如下图:
vue-cli创建项目完成后,按照下图在store目录下创建文件
编写测试代码
a.js代码
const state = {
varA: 0
}
const mutations = {
SET_A: (state, value) => {
state.varA = value
}
}
const actions = {
setVarA({ commit }, value) {
commit('SET_A', value)
},
setA({ dispatch }, value) {
dispatch('b/setVarB', value, { root: true })
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
b.js代码
const state = {
varB: 0
}
const mutations = {
SET_B: (state, value) => {
state.varB = value
}
}
const actions = {
setVarB({ commit }, value) {
commit('SET_B', value)
},
setB({ dispatch }, value) {
dispatch('a/setVarA', value, { root: true })
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
index.js代码
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)
// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
// set './app.js' => 'app'
const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
const value = modulesFiles(modulePath)
modules[moduleName] = value.default
return modules
}, {})
const store = new Vuex.Store({
modules
})
export default store
App.vue代码
<template>
<div id="app">
<h1>test vuex</h1>
<h2>module A:{{ a }}</h2>
<h2>module B:{{ b }}</h2>
<input type="text" v-model="value">
<button @click="handleA">设置A</button>
<button @click="handleB">设置B</button>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
data () {
return {
value: 0
}
},
computed: {
...mapState({
a: state => state.a.varA,
b: state => state.b.varB
})
},
methods: {
handleA () {
this.$store.dispatch('a/setA', this.value)
},
handleB () {
this.$store.dispatch('b/setB', this.value)
}
},
}
</script>
<style lang="scss">
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
</style>
测试结果
在输入框输入, 点击按钮A,module B发生变化,点击按钮B, module A发生变化