该节教程代码可经过npm start运行devServer,在http://localhost:8080/#/index查看效果vue
运行服务端请cd server,node server.js。node
咱们能够新建两个Vuex模块,名为src/store/mod_a.js和src/store/mod_b.js。 每一个Vuex模块均可以看作一个独立的store对象,里面能够有属于它本身的State、Actions、Mutations等等。git
代码示例:/lesson24/src/store/mod_a.jsgithub
新建模块代码以下:vuex
export default {
state: {
str: 'store_a'
},
mutations: {
'mod_a.setStr': function (state, s){
alert('a的setStr');
state.str=s;
}
},
actions: {
'mod_a.setStr': function ({commit}, s){
commit('mod_a.setStr', s);
}
}
}
复制代码
在实例化Store对象时,能够引入模块。npm
import ModA from './mod_a'
import ModB from './mod_b'
复制代码
同时将模块配置到Store中:bash
export default new Vuex.Store({
modules: {
mod_a: ModA,
mod_b: ModB
}
})
复制代码
代码示例:/lesson24/src/components/Index.vueless
在组件中,就能够经过$store.state.mod_a.str读取到模块内的state。async
a_str: {{$store.state.mod_a.str}}<br>
b_str: {{$store.state.mod_b.str}}<br>
复制代码
固然更推荐的是使用mapState的方式读取,可是和直接读取Store下的值(...mapState(['a', 'b']))不一样,读取模块中的State须要经过方法获取:ui
computed: {
...mapState({
str_a: state=>state.mod_a.str,
str_b: state=>state.mod_b.str,
}),
}
复制代码
这样就能够在template中经过str_a和str_b获取到模块的state。
a_str: {{str_a}}<br>
b_str: {{str_b}}<br>
复制代码
假设每一个模块中都有一个名为setStr的Action,咱们在运行this.$store.dispatch('setStr', 'test')时,全部模块中的同名Action都会被执行。
Mutation也具备一样的特色。但这不是Vuex的Bug,它的用意是让使用者可以经过一个Action同时更新多个模块的数据。
若须要回避这个问题,则能够给每一个模块中的Action单独命名,一般咱们会加上模块名做为前缀:
代码示例:/lesson24/src/store/mod_a.js
export default {
state: {
str: 'store_a'
},
mutations: {
'mod_a.setStr': function (state, s){
alert('a的setStr');
state.str=s;
}
},
actions: {
'mod_a.setStr': function ({commit}, s){
commit('mod_a.setStr', s);
}
}
}
复制代码
在使用时,只须要分别mapActions:
代码示例:/lesson24/src/components/Index.vue
此时有两种方法能够mapActions:
完整示例代码以下:
<template>
<div>
str: {{$store.state.str}}<br>
a_str: {{$store.state.mod_a.str}}<br>
b_str: {{$store.state.mod_b.str}}<br>
a_str: {{str_a}}<br>
b_str: {{str_b}}<br>
<input type="button" value="设置A" @click="setA('aa')">
<input type="button" value="设置B" @click="setB('bb')"><br/>
<input type="button" value="设置A" @click="set_a('aaa')">
<input type="button" value="设置B" @click="set_b('bbb')">
</div>
</template>
<script>
import {mapState, mapActions, mapGetters} from 'vuex';
export default {
name: 'Index',
data () {
return {
}
},
async created(){
await this.readUsers();
},
methods: {
...mapActions(['addA', 'addB', 'setOnline', 'readUsers', 'mod_a.setStr', 'mod_b.setStr']),
...mapActions({
set_a: 'mod_a.setStr',
set_b: 'mod_b.setStr'
}),
setA(str) {
this['mod_a.setStr'](str)
},
setB(str) {
this['mod_b.setStr'](str)
},
},
}
</script>
复制代码