一.state
state为单一状态树,在state中需要定义我们所需要管理的数组、对象、字符串等等,只有在这里定义了,在Vue.js的组件中才能获取你定义的这个对象的状态。state是响应式的: 如果修改了数据,相应的在视图上的值也会变化。
在组件中,通过this.$store.state.属性名 来访问。
二.mutations
更改store中state状态的唯一方法就是提交mutation,每个mutation都有一个字符串类型的事件类型和一个回调函数,我们需要改变state的值就要在回调函数中改变。我们要执行这个回调函数,那么我们需要执行一个相应的调用方法:store.commit
定义格式:
new Vue.store({
mutations:{
mutation名1:function(state [, 载荷]) {
},
mutation名2:function(state [, 载荷]) {
}
}
})
使用: this.$store.commit('mutation名', 实参)
三.getters
getter有点类似Vue.js的计算属性,当我们需要从store的state中派生出一些状态,那么我们就需要使用getter,getter会接收state作为第一个参数,而且getter的返回值会根据它的依赖被缓存起来,只有getter中的依赖值(state中的某个需要派生状态的值)发生改变的时候才会被重新计算。
定义格式:
new Vuex.store({
getters: {
// state 就是上边定义的公共数据state
getter的名字1: function(state) {
return 要返回的值
}
}
})
使用:$store.getters.getter的名字
四.actions
action可以提交mutation,在action中可以执行store.commit,而且action中可以有任何的异步操作。在页面中如果我们要调用这个action,则需要执行store.dispatch。
定义格式:
new Vuex.store({
// 省略其他...
actions: {
// context对象会自动传入,它与store实例具有相同的方法和属性
action的名字: function(context, 载荷) {
// 1. 发异步请求, 请求数据
// 2. commit调用mutation来修改数据
// context.commit('mutation名', 载荷)
}
}
})
使用:this.$store.dispatch('actions的名字', 参数)
五.modules
module其实只是解决了当state中很复杂冗余的时候,module可以将store分割成模块,每个模块中拥有自己的state、mutation、action、getter。
访问modules中的数据:
获取数据项: {{$store.state.模块名.数据项名}}
获取getters: {{$store.getters['模块名/getters名']}}
$store.commit('模块名/mutations名') // namespaced为true
$store.dispatch('模块名/actions名') // namespaced为true