什麼是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'
])
}
}