vuex的使用步骤:
使用场景:1、多个组件之间的状态共享、数据共享 2、路由之间的复杂数据传递
vuex的代码通常放在src——》store目录下
- 入口:index.js
- 所有状态:state.js
- 对state做一些映射:getters.js
- 更改 Vuex 中的状态的唯一方法是提交 mutation:mutations.js
- 存储mutation相关的字符串常量: mutation-types.js
- 异步操作、异步修改,或者对mutation的封装:actions.js
1、定义state:考虑清楚原始数据是什么,最好是底层数据
state唯一数据源
mapState辅助函数:使用 mapState 辅助函数帮助我们生成计算属性
computed:{
...mapState(['','']);
}
2、getters:对数据的映射,可以是函数或者写比较复杂的判断逻辑
mapGetters 辅助函数:仅仅是将 store 中的 getter 映射到局部计算属性
computed:{
...mapGetters(['','']);
}
3、mutation-types:定义需要的修改的动作,一般是动词SET_加上state定义的状态,定义成字符串常量
4、mutations:定义数据修改逻辑,实际是个函数,函数名就是mutation-types定义的字符串常量
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit
('increment')`// `mapMutations` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit ('increment')`
})
}
}
5、actions操作:
- 异步操作
- 对mutation的封装(通过调用一个action来达到修改多个mutation的目的)
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
// `mapActions` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this. $store.dispatch('increment')`
})
}
}