什么是Module?
Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块
{
moduleA: {
state: {},
mutation: {},
action: {},
getters: {}
},
moduleB: {
state: {},
mutation: {},
action: {},
getters: {}
}
}
用到Module常见的会遇到命名空间 ,此时commit,dispatch,getters会发现一些变化
举个例子
{
state: {},
mutation: {},
action: {},
module: {
moduleA: {
namespaced: true,
state: {},
mutation: {
add(){} // 访问时需要 this.$store.commit('moduleA/add')
},
action: {
add(){} // 访问时需要 this.$store.dispatch('moduleA/add')
},
getters: {
getState(){} // 访问时需要 this.$store.getters['moduleA/getState']
}
}
}
}
在带命名空间的模块注册全局 action
{
state: {},
mutation: {},
action: {},
module: {
moduleA: {
namespaced: true,
state: {},
mutation: {
add(){} // 访问时需要 this.$store.commit('moduleA/add')
},
action: {
add(){} // 访问时需要 this.$store.dispatch('moduleA/add')
addTwo: {
root: true,
handler(context) {}
} // 访问时需要this.$store.dispatch('addTwo')
},
getters: {
getState(){} // 访问时需要 this.$store.getters['moduleA/getState']
}
}
}
}
带命名空间的绑定函数
computed: {
...mapState({
a: state => state.moduleA.a
})
},
methods: {
...mapActions([
'moduleA/add' // -> this['smoduleA/add']()
])
}
// 或者
computed: {
...mapState('moduleA', {
a: state => state.a
})
},
methods: {
...mapActions('moduleA', [A
'add' // -> this.add()
])
}
// 或者
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapActions } = createNamespacedHelpers('moduleA')
export default {
computed: {
// 在 `moduleA` 中查找
...mapState({
a: state => state.a
})
},
methods: {
// 在 `moduleA` 中查找
...mapActions([
'add'
])
}
}