state就是全局的状态(数据源),我们可以用以下方式在Vue 组件中获得Vuex的state状态
template
{{ $store.state.count }}
script
console.log(this.$store.state.count)
getters其实可以认为是 store 的计算属性,用法和计算属性差不多。
定义getter:
getters: {
done(state) {
return state.count + 5;
},
}
使用getter
console.log(this.$store.getters.done)
mutations是操作state的唯一方法,即只有mutations方法能够改变state状态值。
mutations对state的操作
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
组件通过commit提交mutations的方式来请求改变state
this.$store.commit('increment')
这样的好处是我们可以跟踪到每一次state的变化,以便及时分析和解决问题。
mutations方法中是可以传参的,具体用法如下:
mutations: {
// 提交载荷 Payload
add(state, n) {
state.count += n
}
},
this.$store.commit('add', 10)
这里只是传了一个数字,在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读。
mutations方法必须是同步方法!
之前说mutations方法必须只能是同步方法,为了处理异步方法,actions出现了。关于action和mutations的区别有以下几点:
actions: {
increment (context) {
context.commit('increment')
},
incrementAsync (context) {
// 延时1秒
setTimeout(() => {
context.commit('increment')
}, 1000)
}
},
不同于mutations使用commit方法,actions使用dispatch方法。this.$store.dispatch('incrementAsync')
context是与 store 实例具有相同方法和属性的对象。可以通过context.state
和context.getters
来获取 state 和 getters。
incrementAsyncWithValue (context, value) {
setTimeout(() => {
context.commit('add', value)
}, 1000)
}
this.$store.dispatch('incrementAsyncWithValue', 5)
使用单一状态树,导致应用的所有状态集中到一个很大的对象。但是,当应用变得很大时,store 对象会变得臃肿不堪。
为了解决以上问题,Vuex 允许我们将 store 分割到模块(module)。每个模块拥有自己的 state、mutation、action、getters、甚至是嵌套子模块——从上至下进行类似的分割:
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态