注:本文内容主要来源于 Vuex 官网
https://vuex.vuejs.org/zh/guide/state.html
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,采用集中式存储管理应用的所有组件的状态;
适用于中大型的单页面应用程序;
// src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: { ... }, // 存储 store 状态(数据)
getters: { ... },
mutations: { ... },
actions: { ... },
modules: { ... }
})
getters
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
},
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
mutations
Mutation 用于更新 store 的数据,它的内容必须是同步函数
// store
state: {
count: 1
},
mutations: {
increment (state, payload) {
state.count += payload
}
}
// 唤醒 Mutation
store.commit('increment', 10);
// 对象风格提交
store.commit({
type: 'increment',
amount: 10
}) // increment 内部: state.count += payload.amount
// 对 store 里的的对象添加属性;
Vue.set(obj, 'newProp', 123)
// 或者
state.obj = { ...state.obj, newProp: 123 }
Action
-
Action 提交的是 mutation,而不是直接变更状态;
-
Action 可以包含任意异步操作;
actions: {
incrementAsync ({ commit }, payload) {
setTimeout(() => {
commit('increment');
}, 1000)
}
}
// 分发 action
// 以载荷形式分发
store.dispatch('incrementAsync', { amount: 10 }) // payload.amount 获取 10
// 以对象形式分发
store.dispatch({
type: 'incrementAsync',
amount: 10
}) // payload.amount 获取 10
Module
const moduleA = {
namespaced: true, // 开启命名空间,mutations... 里的方法就可以与外部重名
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
// 访问状态
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
命名空间
访问 module 内 getters, actions, mutations 的方法;
const store = new Vuex.Store({
modules: {
account: {
namespaced: true,
// 模块内容(module assets)
state: () => ({ ... }), // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响
getters: {
isAdmin () { ... } // -> getters['account/isAdmin']
},
actions: {
login () { ... } // -> dispatch('account/login')
},
mutations: {
login () { ... } // -> commit('account/login')
},
// 嵌套模块
modules: {
// 继承父模块的命名空间
myPage: {
state: () => ({ ... }),
getters: {
profile () { ... } // -> getters['account/profile']
}
},
// 进一步嵌套命名空间
posts: {
namespaced: true,
state: () => ({ ... }),
getters: {
popular () { ... } // -> getters['account/posts/popular']
}
}
}
}
}
})
辅助函数 mapState & mapGetters
import { mapState } from 'vuex';
computed: {
// 原有的计算属性
localComputed () { /* ... */ },
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
}),
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
...mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})
}
}
mapMutations & mapActions
import { mapMutations, mapActions } from 'vuex'
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
// `mapMutations` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
// `mapActions` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}