Vuex
什么是Vuex?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
简单来说,Vuex就是一个为Vue设计的集中式状态管理仓库,它将Vue中共享的状态从组件中抽离出来,进行统一规范地管理。
为什么要用Vuex?
当多个组件嵌套、兄弟组件通信、不相干组件通信时,使用传统的组件间通信方式将会非常繁琐,而且通常会产生无法维护的代码。为了便于复杂项目中的组件通信和状态维护,可以使用Vuex对项目中的状态进行集中式管理。
Vuex的核心概念
1、State
State是Vuex中用来存储状态的对象,它是Vuex中唯一的数据源
使用:
1、this.$store.state.xxx
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
2、mapState辅助函数
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
export default {
// ...
computed: {
...mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
}
当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
computed: mapState([
// 映射 this.count 为 store.state.count
'count'
])
2、Getters
当我们需要从state中派生出一些状态时,我们可以使用Getters(类似于计算属性)。Getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
Getter 接受 state 作为其第一个参数:
getters:{
doneTodos(state){
return state.todos.filter(todo=>todo.done)
}
}
Getter 也可以接受其他 getter 作为第二个参数:
getters:{
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
通过让 Getter 返回一个函数,来实现给 getter 传参:
getters: {
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
this.$store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
// 注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。
使用:
1、this.$store.getters.xxx
2、mapGetters辅助函数
import { mapGetters } from 'vuex'
export default {
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
])
}
}
如果你想将一个 getter 属性另取一个名字,使用对象形式:
...mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})
3、Mutations
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler),该回调函数接受state作为第一个参数,若要向mutation传递额外的参数,可以通过第二个参数载荷(payload)。在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读。
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state, payload) {
// 变更状态
state.count+=payload.num
}
}
})
使用:
1、this.$store.commit('xxx',payload)
this.$store.commit('increment', {
amount: 10
})
2、对象风格的提交方式
this.$store.commit({
type: 'increment',
amount: 10
})
3、mapMutations辅助函数
import { mapMutations } from 'vuex'
export default {
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')`
})
}
}
**注意:**Mutation必须是同步函数,在 mutation 中混合异步调用会导致你的程序很难调试
4、Actions
Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit
提交一个 mutation,或者通过 context.state
和 context.getters
来获取 state 和 getters。若要向action传递额外的参数,可以通过第二个参数载荷(payload)。
actions: {
increment (context, payload) {
context.commit('increment', payload.num)
},
checkout ({ commit, state }, products) {
// 把当前购物车的物品备份起来
const savedCartItems = [...state.cart.added]
// 发出结账请求,然后乐观地清空购物车
commit(types.CHECKOUT_REQUEST)
// 购物 API 接受一个成功回调和一个失败回调
shop.buyProducts(
products,
// 成功操作
() => commit(types.CHECKOUT_SUCCESS),
// 失败操作
() => commit(types.CHECKOUT_FAILURE, savedCartItems)
)
}
}
使用:
1、this.$store.dispatch('xxx', payload)
store.dispatch('increment', 2)
2、对象形式
store.dispatch({
type: 'incrementAsync',
amount: 10
})
3、mapActions辅助函数
import { mapActions } from 'vuex'
export default {
methods: {
...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')`
})
}
}
组合Action
store.dispatch
可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch
仍旧返回 Promise。
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
}
}
this.$store.dispatch('actionA').then(() => {
// ...
})
// 利用async/await
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}
**注意:**一个 store.dispatch
在不同模块中可以触发多个 action 函数。在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行。
5、Modules
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:
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 的状态
命名空间:
默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。
如果希望你的模块具有更高的封装度和复用性,你可以通过添加 namespaced: true
的方式使其成为带命名空间的模块。
// moduleA.js
const state = {}
const getters = {}
const mutations = {}
const actions = {}
export {
namespaced: true,
state,
getters,
mutaions,
actions
}
// store/index.js
import moduleA from './modules/moduleA'
export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {
moduleA,
},
})