Vuex 使得在 Vue 组件中可以跨组件共享同一个或多个状态,但是如何避免在不同的组件中重复引用 store 呢?
定义 store 结构
const state = {
modules: {
moduleA: {
state: {
name: 'moduleA'
},
mutations: {
setName: (state, name) => {
sate.name = name
}
}
},
moduleB: {
state: {
title: 'moduleB'
},
mutations: {
setTitle: (state, title) => {
sate.title = title
}
}
}
}
}
js
通过 this.$store.xxx 直接使用
this.$store.state.moduleA.name
this.$store.commit('moduleA/setName')
js
mapState,mapMutations 的使用
<script>
import { mapMutations, mapState } from 'vuex'
export default {
computed: {
...mapState('moduleA', [
'name'
])
},
methods: {
...mapMutations('moduleA', [
'setName'
])
}
}
</script>
vue
this.name // this.$store.state.moduleA.name
this.setName() // this.$store.commit('moduleA/setName')
js
使用 createNamespacedHelpers 简化 mapXXX 的映射
<script>
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapMutations } = createNamespacedHelpers('moduleA')
export default {
computed: {
...mapState([
'name'
])
},
methods: {
...mapMutations([
'setName'
])
}
}
</script>
vue
使用 mixins 选项
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapMutations } = createNamespacedHelpers('moduleA')
export default {
computed: {
...mapState([
'name'
])
},
methods: {
...mapMutations([
'setName'
])
}
}
js
<script>
import moduleAMixin from 'path/to/moduleAMixin.js'
export default {
mixins: [moduleAMixin]
}
</script>
vue
对于 moduleB 或者其他任何你想跨组件共享的 store 模块,都可以使用类似的方式
提示:关于
mapGetters与mapActions的使用
mapGetters与mapState的使用方式一致mapActions与mapMutations的使用方式一致
总结
- 跨组件共享同一个模块的状态,使用
mixin选项配合 Vuex 的createNamespacedHelpers,mapState,mapMutations,mapGetters,mapActions可以将组件内部的 store 相关代码量降到很低的程度 - 即使有了 Vuex,也并不意味着你需要将所有的数据都放到 Store 里,我坚持认为只有当需要跨组件共享状态时才使用 Vuex 才是正确的做法,否则就是徒增代码量而已
评论