State
state属性是Vuex中用于存放组件之间共享的数据;也就是说,我们把一些组件之间共享的状态主要存放在state属性中;它采用的是单一状态树——用一个对象就包含了全部的应用层级状态。这也意味着,每个应用将仅仅包含一个 store 实例。单一状态树让我们能够直接地定位任一特定的状态片段,在调试的过程中也能轻易地取得整个当前应用状态的快照。
Mutations
1.提交mutation是更改Vuex的store中的状态的唯一方法
2.Vuex中的mutation非常类似于事件
3.每个mutation都有一个事件类型(type)和一个回调函数(handler)
4.这个回调函数就是我们实际进行状态更改的为地方,它会接收一个state作为第一个参数
Store中index.js中的muttions中的方法
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
store.commit('increment')
提交载荷
// ...
mutations: {
//方法
increment(state){
state.counter++
},
//store.commit传入额外参数
//提交载荷
increment2(state, n) {
state.counter += n
},
//载荷为对象,这样可以包含多个字段,mutation会更易读
increment3(state, payload) {
state.counter += payload.amount;
},
decrement(state){
state.counter--
}
},
methods:{
addition(){
//语法 this.$store.commit('mutation中的方法名')
this.$store.commit('increment3',{amount:100})
console.log(this.$store.state.counter)
},
subtraction(){
this.$store.commit('decrement')
},
updateInfo(){
this.$store.commit('updateInfo')
}
}
使用常量替代Mutation事件类型
mutations-types.js
app
store中的index.js
Mutations中必须是同步操作,否则devtools不能很好的跟踪这个操作什么时候被完成
比如:
在mutations中使用异步操作:
异步前
页面:
VueX:
异步后
页面:
VueX:我们会发现并没有跟踪到
为了解决异步更改state状态,使用Actions
Actions
Actions 类似于mutations,不同在于
- Action 提交的是 mutation,而不是直接变更状态
- Action 可以包含任意异步操作
例子:
app中方法 使用this.$store.dispatch(‘actions中的方法名’)
actions中方法:
此处才提交commit到mutations
此时,页面异步更改,VueX中跟着更改:
使用promise回调:
Getters
1.有时候我们需要从 store 中的 state 中派生出一些状态
2.多个组件需要某一状态,且需要对其做一定变化的情况下使用,可以直接使用getter,不用在组件内重新方法或commit mutation写重复的方法
app中
app的components中
Store 的index.js中
Module
1.定义模块:
2.App中使用模块中的state:
这里需要注意写法:$store.state.a.name a是模块名
3.App中提交模块中的Mutations:
4.模块中的Getters的使用
5.模块中Actions的使用