Vuex是vue的状态管理工具,为了更方便的实现多个组件共享状态
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 0
}
})
new Vue({
store,
})
state
单一状态树,使用一个对象就包含了全部的应用层级状态
通过store提供了一种机制将状态从根组件“注入”到每一个子组件中
该store实例会注入到根组件下的所有组件中,且子组件可以通过this.$store访问
<div class="home">
{{ $store.state.count }}
</div>
mapState 辅助函数
需要获取多个状态时,我们可以使用mapState辅助函数帮助我们生成计算属性:
import { mapState } from 'vuex';
computed: {
...mapState(['count']),
},
Mutation
更改Vuex的store中的状态的唯一方法是提交mutation
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
不能直接调用一个mutation handler。这个选项更像是事件注册:“当触发一个类型为increment的mutation时,调用次函数。”:
this.$store.commit('increment');
在组件中提交 Mutation
import { mapMutations } from 'vuex'
export default {
// ...
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}
}
提交载荷(Payload)
你可以向store.commit传入额外的参数,即mutation的载荷(payload):
mutations: {
increment (state, n) {
state.count += n
}
}
this.$store.commit('increment', 10)
Action
Action类似于mutation,不同在于:
Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
分发Action
thsi.$store.dispatch('increment')
虽然和mutation差不多,但是在action中,可以执行异步操作,但是mutation中不行!!!
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
组合 Action
Action 通常是异步的,那么如何知道 action 什么时候结束呢?
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
}
}
this.$store.dispatch('actionA').then(() => {
// ...
})