Vuex的五个核心概念:state、getters、mutations、actions、modules
1、state: vuex的基本数据,用来存储变量;
2、getters: 从基本数据(state)派生的数据,相当于state的计算属性;
3、mutations: 提交更新数据的方法,必须是同步的(如果需要异步使用action)。每个mutation 都有一个字符串的事件类型(type)和一个回调函数(handler)。
回调函数就是我们实际进行状态更改的地方,并且它会接受 state作为第一个参数,提交载荷作为第二个参数。
4、action: 和mutation的功能大致相同,不同之处在于 ①Action提交的是mutation,而不是直接变更状态,②Action可以包含任意异步操作。
5、modules: 模块化vuex,可以让每一个模块拥有自己的 state、mutation、action、 getters,使得结构非常清晰,方便管理。
1、声明(state)
state: {
price:0,
},
2、使用(state)
import {mapState} from 'vuex'
computed:{
...mapState(['price',"number"]),
},
3、修改声明的变量(mutations)
SetPrice(state,x){
state.price=x;
},
4、使用修改声明的变量(mutations)
import {mapMutations} from 'vuex'
methods: {
...mapMutations(['SetPrice']),
this.SetPrice(3)
}