Vue 应用的核心就是 store (仓库)。它包含着你应用种的大部分状态(state)。Vuex 和单纯的全局对象有两点不同:
- Vuex 的状态存是响应式的,当 Vue 组件从 store 中读取的**状态(state)**发生改变时,组件也会也会得到更新
- 不能直接改变 store 中的 state,需要通过显示的提交(commit) mutation。
先写一个最简单的 Store,方便后面的理解。
这里是在 vue-cli 中构建项目的实例:
当然我们需要在入口文件 main.js 中引入 store,这个应该在项目起始就已经引入了。
然后在组件中我们要改变state:
this.$store.commit('updateChooseStaffInfo',JSON.stringify(staffInfo));
这里我们要掌握五个核心对象:
- State
- Getter
- Mutation
- Action
- Module
不要停,下面让我们直接一次性把这五个概念了解学会。
一、State
前面提到了,它代表了 Vuex 的状态。简单来说,就是多个组件需要共享的字段对象要写在state
里面。像上面代码:
state:{
chooseStaffInfoId:'',
chooseStaffInfo:'',
},
当我们在组件中需要获取 state 中的值时,可以这样获取:
this.$store.state.chooseStaffInfoId;
二、Getter
有时候,我们需要从 store
中的 state
派生出一些状态,或者需要对state
中的某些属性做些处理时,可以用到它。
在上面的代码中,因为浏览器刷新会导致我们在state
中定义的属性变量回归到初始定义的值,而在组件中需要实时跟着值得变化,所以在sessionStorage
中也存了一份。
getters:{
getChooseStaffInfoId:function (state) {
if(!state.chooseStaffInfoId){
state.chooseStaffInfoId = sessionStorage.getItem('chooseStaffInfoId');
}
return state.chooseStaffInfoId;
},
getChooseStaffInfo:function (state) {
if(!state.chooseStaffInfo){
state.chooseStaffInfo = sessionStorage.getItem('chooseStaffInfo');
}
return state.chooseStaffInfo;
},
},
这样无论浏览器是否刷新,我们都能获取到改变的属性值,在组件中获取方式为:
//这里将获取到 state 中的 chooseStaffInfoId 属性值
let staffInfoId = this.$store.getters.getChooseStaffInfoId;
注意:Getter
接受 state
作为其第一个参数,也可以接受其他getter
作为第二个参数
mapState 辅助函数
当一个组件需要获取多个状态时,我们一个一个的去获取会比较麻烦。因此,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
}
})
}
或者使用扩展运算符:
computed: {
localComputed () { /* ... */ },
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
// ...
})
}
mapGetters 辅助函数
它仅仅是将 store
中的 getter
映射到局部计算属性。简单来说,就是可以把getters
中的所有或者部分属性抽取出来放到计算属性里面:
import { mapGetters } from 'Vuex'
export default {
//...
computed: {
...mapGetters([
// 使用对象展开运算符将 getter 混入 computed 对象中
'getChooseStaffInfoId',
'getChooseStaffInfo',
// ...
])
}
}
如果你想将一个getter
属性另取一个名字,使用对象形式:
mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})
三、Mutation
最开始的我们讲过,改变 state
的唯一途径就是通过提交(commit)
mutation。
它接受state
作为第一个参数:
上面代码
mutations:{
updateChooseStaffInfoId(state,chooseStaffInfoId){
sessionStorage.setItem('chooseStaffInfoId',chooseInfoId);
state.chooseStaffInfoId = chooseStaffInfoId;
}
}
在组件中,我们可以这样调用mutation
中的方法:
//第二个参数,相对于方法中的 chooseStaffInfoId
this.$store.commit('updateChooseStaffInfoId','MT1245');
需要注意的事项:
- 最好提前在 store 中初始化好所有所需属性
Mutation
必须是同步函数
mapMutations辅助函数
可以将组件中的methods
映射为 store.commit
调用(需要在根节点注入store
)
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')`
})
}
}
四、Action
它类似于mutation
,不同在于:
Action
提交的时mutation
,而不是直接变更状态Action
可以包含任意异步操作
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
Action
函数接收一个与store
实例具有相同方法和属性的 context
对象,因此可以调用context.commit
提交一个mutation
或者可以通过contex.state
和context.getters
来获取state
和getters
。但是context
对象并不是store
实例本身。
我们调用Action
的方法称为 分发 Action。触发方法:
store.dispatch('incream')
使用到 Action
,最主要的就是它可以进行异步操作。
actions: {
// 这里对象 { commit, state } 用到 ES2015 的 参数解构 来简化代码(特别是我们需要调用 commit 很多次的时候)
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)
)
}
}
你在组件中使用 this.$store.dispatch('xxx')
分发 action
,或者使用 mapActions
辅助函数将组件的 methods
映射为 store.dispatch
调用(需要先在根节点注入 store
):
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')`
})
}
}
五、Module
由于使用单一状态树,应用的所有状态都集中到一个对象里面,会使得store
对象变的臃肿。
为了解决以上问题,Vuex 允许将store
分割成模块(module)。每个模块拥有自己的state
,getter
、moutation
、action
、甚至是嵌套模块。
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 的状态
对于模块内部的 mutation
和 getter
,接收的第一个参数是模块的局部状态对象。
const moduleA = {
state: { count: 0 },
mutations: {
increment (state) {
// 这里的 state
对象是模块的局部状态
state.count++
}
},
getters: {
doubleCount (state) {
return state.count * 2
}
}
}
同样,对于模块内部的 action
,局部状态通过 context.state
暴露出来,根节点状态则为 context.rootState
:
const moduleA = {
// ...
actions: {
incrementIfOddOnRootSum ({ state, commit, rootState }) {
if ((state.count + rootState.count) % 2 === 1) {
commit('increment')
}
}
}
}
对于模块内部的 getter,根节点状态会作为第三个参数暴露出来:
const moduleA = {
// ...
getters: {
sumWithRootCount (state, getters, rootState) {
return state.count + rootState.count
}
}
}
当然,还有一个其他的一些东西,比如命名空间等,这个感兴趣可以自行了解Vuex
总结:
一般的项目中我们只用到state
、getter
和mutation
就够了,当业务逻辑非常复杂时才会用到其他的,实践才能让我们更好的了解,所以一定要动手写一遍。