export default () => {
return new Vuex.Store({
modules: {
a: {
state: {
text: 1
}
},
b: {
state: {
text: 2
}
}
}
})
}
computed: {
textA () {
return this.$store.state.a.text // 1
}
}
或者
...mapState({
textA: (state) => state.a.text
})
直接可以在mapMutations中使用modules中的mutation
modules: {
a: {
state: {
text: 1
},
mutations: {
updateText (state, text) {
console.log('a.state', state)
state.text = text
}
}
}
}
mounted () {
this.updateText('123')
},
methods: {
...mapMutations(['updateText'])
}
modules: {
a: {
namespaced: true,
state: {
text: 1
},
mutations: {
updateText (state, text) {
console.log('a.state', state)
state.text = text
}
}
}
}
有命名空间时的调用方式
mounted () {
this['a/updateText']('123')
},
methods: {
...mapMutations(['a/updateText'])
}
modules: {
a: {
namespaced: true,
state: {
text: 1
},
getters: {
textPlus (state) {
return state.text + 1
}
}
}
}
computed: {
...mapGetters({
textPlus: 'a/textPlus'
})
}
getters: {
textPlus (state, getters, rootState) {
return state.text + rootState.count
}
}
getter调用另一个module的state
getters: {
textPlus (state, getters, rootState) {
return state.text + rootState.b.text
}
}
actions: {
add ({state, commit, rootState}) {
commit('updateCount', rootState.count)
}
}
此时,控制台会报错[vuex] unknown local mutation type: updateCount, global type: a/updateCount
需要允许module调用全局的mutation
add ({state, commit, rootState}) {
commit('updateCount', {num: 999}, {root: true})
}
modules: {
a: {
namespaced: true,
state: {
text: 1
},
mutations: {
updateText (state, text) {
console.log('a.state', state)
state.text = text
}
}
},
b: {
actions: {
testAction ({commit}) {
commit('a/updateText', 'test text')
}
}
}
}
mounted () {
this.testAction()
},
methods: {
...mapActions(['testAction'])
}
给modules b 加上命名空间
b: {
namespaced: true,
state: {
text: 2
},
actions: {
testAction ({commit}) {
commit('a/updateText', 'test text', {root: true})
}
}
}
此时调用也需要加上命名空间
mounted () {
this['b/testAction']()
},
methods: {
...mapActions(['b/testAction'])
}
module中也可嵌套模块
// main.js
store.registerModule('c', {
state: {
text: 3
}
})
export default () => {
const store = new Vuex.Store({
strict: isDev,
state: defaultState,
mutations,
getters,
actions
})
if (module.hot) {
module.hot.accept([
'./state/state',
'./mutations/mutations',
'./getters/getters',
'./action/action'
], () => {
const newState = require('./state/state').default
const newMutations = require('./mutations/mutations').default
const newGetters = require('./getters/getters').default
const newActions = require('./action/action').default
store.hotUpdate({
state: newState,
mutations: newMutations,
getters: newGetters,
actions: newActions
})
})
}
return store
}