Vuex是Vue.js中的状态管理模式,它充当应用程序中所有组件的集中存储。Vuex帮助开发人员使用一套原则以一种更有组织的方式组织他们的项目。
在了解这些原理之前,需要先了解Vuex store的4个主要组件:
- States: 用于保存您的应用程序的数据
- Getters:用于访问store外部的这些状态对象。
- Mutations:用于修改状态对象。
- Actions:用于提交突变。
遵循的原则如下:
- 你需要将应用程序级状态集中存储在store中。
- 状态应该总是通过提交mutations而发生突变。
- 异步逻辑应该被封装,并且只能与Action一起使用。
主要项目结构如下所示:
├── index.html
├── main.js
├── api
├── components
└── store
├── index.js
├── actions.js
├── mutations.js
└── modules
模块化Vuex store
需要管理好store,并且需要避免store拥挤,因此,建议对你Vuex store进行模块化。在一个项目中,没有确定的模块分解方式,有的开发人员根据功能进行模块化,而有的开发人员则根据数据模型进行模块化。关于模块化的最终决定完全取决于项目的结构,处理好模块化将有助于该项目的长期发展。
store/
├── index.js
└── modules/
├── module1.store.js
├── module2.store.js
├── module3.store.js
├── module4.store.js
└── module5.store.js
使用助手来简化你的代码
在前面提到的Vuex store中使用的4个组件。让我们考虑一种情况,即你需要访问这些states、getters,或者你需要调用组件中的action、mutations。在这种情况下,你不需要创建多个计算属性或方法,你可以很容易地使用辅助方法(mapState
、mapGetters
、mapMutations
和 mapActions
)来减少代码。让我们来看看这四个辅助工具:
mapState
如果我们需要在一个组件中调用多个store states属性或getters,我们可以使用 mapState
帮助来生成一个获取器函数,这将大大减少代码行数。
import { mapState } from 'vuex'
export default {
computed: mapState({
count: state => state.count,
countAlias: 'count',
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
mapGetters
mapGetters
帮助程序可以用来将store getters映射到本地计算属性。
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters([
'count1',
'getter1',
])
}
}
mapMutations
mapMutations
辅助函数可以用来提交组件中的mutations,并将组件方法映射到 store.commit
调用。同样,我们也可以使用mapMutations传递有效载荷。
import { mapMutations } from 'vuex'
export default {
methods: {
...mapMutations({
cal: 'calculate' // map `this.cal()` to `this.$store.commit('calculate')`
})
}
}
mapActions
此帮助程序用于在组件中分派action,并将组件方法映射到 store.dispatch
调用。
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions({
cal: 'calculate' // map `this.cal()` to `this.$store.dispatch('calculate')`
})
}
}