Vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
“单向数据流”理念的极简示意
state,驱动应用的数据源;
view,以声明方式将 state 映射到视图;
actions,响应在 view 上的用户输入导致的状态变化。
当多个组件共享状态时,单向数据流的简洁性很容易被破坏:
1、多个视图依赖于同一状态:传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力;
2、来自不同视图的行为需要变更同一状态:我们经常会采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝;
Vuex 核心思想
Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。
Vuex基础概念
State
vuex的单一状态树,使用一个对象就包含了应用层的所有状态;state是vuex自己维护的一份状态数据,通过操作去页面渲染;
获取数据:
在 Vue 组件中获得 Vuex 状态:
Vuex 的状态存储是响应式的,从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态:
computed: {
count () {
return this.$store.state.count
}
}
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
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'
])
mapState
函数返回的是一个对象。我们如何将它与局部计算属性混合使用呢
computed: {
localComputed () { /* ... */ },
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
// ...
})
}
computed: {
localComputed () { /* ... */ },
...mapState([
'orderList',
'login'
])
},
mounted () {
console.log(typeof orderList); ==>undefind
console.log(typeof this.orderList)==>object
}
// 别名情况
computed: {
localComputed () { /* ... */ },
...mapState({
orderListAlias: state => state.template.orderList
})
},
mounted () {
console.log(typeof this.orderListAlias)==>object
}
Getters
有时候我们需要从 store 中的 state 中派生出一些状态,getters属性主要是对于state中数据的一种过滤;
Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性);
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})
// 通过属性访问
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
Getter 也可以接受其他 getter 作为第二个参数:
getters: {
// ...
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
// store.getters.doneTodosCount // -> 1
// 组件中使用它
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
通过方法访问:
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
mapGetters
辅助函数:
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
// getter 属性另取一个名字,使用对象形式
mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})
Mutations
this.$store.commit('xxx')
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation;
每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler);
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
// 修改
store.commit('increment')
提交载荷(Payload):
这个store.commit
可以接受传入额外的参数,即 mutation 的 载荷(payload):
// ...
mutations: {
increment (state, n) {
state.count += n
}
}
// 修改
store.commit('increment', 10)
// 载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:
// ...
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
// 修改
store.commit('increment', {
amount: 10
})
// 对象风格的提交方式,直接使用包含 type 属性的对象
// 修改
store.commit({
type: 'increment',
amount: 10
})
Mutation 需遵守 Vue 的响应规则:
- 变更状态时,监视状态的 Vue 组件也会自动更新
- 当需要在对象上添加新属性时,你应该
-
使用
Vue.set(obj, 'newProp', 123)
, 或者 -
以新对象替换老对象。例如,利用 stage-3 的对象展开运算符我们可以这样写:
state.obj = { ...state.obj, newProp: 123 }
使用常量替代 Mutation 事件类型:
// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
// mutations.js
import { SOME_MUTATION } from './mutation-types'
mutations: {
// 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
[SOME_MUTATION] (state) {
// mutate state
}
}
// 如果你不喜欢,你完全可以不这样做;
注意:Mutation 必须是同步函数
在组件中提交 Mutation:
可以在组件中使用 this.$store.commit('xxx')
提交 mutation
使用 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')`
})
}
}
Actions
this.$store.dispatch('xxx')
于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态;
- Action 可以包含任意异步操作;
初步的例子:
actions: {
increment (context) {
context.commit('increment')
}
}
// ES2015 的 参数解构 来简化代码
actions: {
increment ({ commit }) {
commit('increment')
}
}
分发 Action
// Action 通过 store.dispatch 方法触发:
store.dispatch('increment')
这样做的重点在于,可以在 action 内部执行异步操作:
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
Actions 支持同样的载荷方式和对象方式进行分发:
// 以载荷形式分发
store.dispatch('incrementAsync', {
amount: 10
})
// 以对象形式分发
store.dispatch({
type: 'incrementAsync',
amount: 10
})
购物车示例:涉及到调用异步 API 和分发多重 mutation:
actions: {
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)
)
}
}
在组件中分发 Action
使用 mapActions
辅助函数将组件的 methods 映射为 store.dispatch
调用:
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
Action 通常是异步的,action 什么时候结束呢?组合多个 action,以处理更加复杂的异步流程;
首先: store.dispatch
可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch
仍旧返回 Promise:
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
}
}
现在你可以:
store.dispatch('actionA').then(() => {
// ...
})
也可以在另外一个 action 中:
actions: {
// ...
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
commit('someOtherMutation')
})
}
}
最后,如果我们利用 async / await,我们可以如下组合 action:
// 假设 getData() 和 getOtherData() 返回的是 Promise
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}
模块(Module)
因为随着后面的业务逻辑的增多,把vuex分模块的开发会使得代码更加简洁清晰明了,比如登录一个模块,产品一个模块,这样后面改动起来也简单嘛;
https://vuex.vuejs.org/zh/guide/modules.html
项目结构
https://vuex.vuejs.org/zh/guide/structure.html
代码实践
安装依赖
npm install vuex