定义:
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式
简单的理解为一个管理数据的根对象
主要内容:
首先在Vue实例中提前创建好store
new Vue({el: '#app',store: store, // ES6语法可简写为store})
然后就可以在任何一个组件中使用this.$store.commit('方法名')来调用方法this.$store.state.xxx来获取数据
state:数据(设置一个初始值即可)
mutations:所有的方法都放这里(都有一个事件类型和回调函数),必须是同步函数
这个回调函数会接受state作为第一个参数
更改store的状态的方法就是提交mutations
const store = new Vuex.Store({state: {count: 1},mutations: {add (state) {// 变更状态state.count++}}})
不能直接调用其方法,需要使用store.commit('add'),外部组件使用this.$store.commit('add')
参数的形式:可以额外传参(仅能传两个参数,如有第三个使用对象传参)
add(state,n){}add(state,payload: {m,n}) 整个对象作为第二个参数
actions:提交mutations,而不是直接变更状态(可以包含任意异步操作)
actions: {add (context) {context.commit('add')}}// 参数解构actions: {add ({ commit }) {commit('add')}}
modules:
store里面内容也可以分为多个模块,每个模块中又都分为state、mutations、actions
模块的局部状态:
- 对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象(局部的state)
- 对于模块内部的 action,局部状态通过
context.state暴露出来,根节点状态则为context.rootState - 对于模块内部的 getter,根节点状态会作为第三个参数暴露出来 ```javascript 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 的状态 ```
