通过前面四篇,我们已经讲完了Vuex中的四个核心概念,分别是state,getters,mutations,actions掌握了这四个概念,我们基本可以应对一些中小项目了。Vuex中还有最后一个概念是modules,主要是为了针对一些大型复杂项目,避免store里面的数据太多,难以管理而设计存在的,modules比较难,所以本篇先不做详细讲述,会把他放在最后一篇来做解释
今天主要就是想跟大家分享下关于Vuex中存在的一些辅助函数,这些辅助函数可以使我们的代码更简洁,更直观,更好维护。首先要讲的就是mapState,
1.mapState
通过前面第一篇的学习,我们知道如果要读取定义在state里面基本状态,最简单的方法就是从计算属性中返回某个状态。那么当一个组件需要获取多个状态的时候,怎么办,是不是需要这样
export default {
...
computed:{
a() {
return store.state.count
}
b() {
return store.state.isShowToast
}
c() {
return store.state.c
}
d() {
return store.state.d
}
}
}
当然这样写,绝对没有问题的,但是随着状态的越来越多,我们要写很多计算属性,这样看起来绝对非常难受,于是,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
}
})
}
从以上代码可以看出mapState函数返回的是一个对象,我们可以把需要用到的状态放到mspState里面进行统一管理,还可以取别名来使用。
如果所映射的计算属性跟state子节点的名称相同的时候,给mapState传一个数组,可以使代码更加简化:
computed: mapState([
// 映射 this.c 为 store.state.c,映射this.d 为store.state.d
'c',
'd',
])
如果我们是半路上的Vuex,在不改动以前的写好的计算属性下,怎么跟局部的计算属性混合使用呢,那就用到了对象扩展运算符
computed: {
localComputed () {
...
},
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
// ...
})
}
在了解了mapState函数后,接下来的几个辅助函数跟mapState有异曲同工之处,我们接着往下看:
2.mapGetters
这个和 mapState 基本上没啥区别,简单看下下面的例子,就懂了:
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'appleCount',
'apple',
// ...
])
}
}
如果你想将一个 getter 属性另取一个名字,可以使用对象的形式:
mapGetters({
// 把 `this.doneApple` 映射为 `this.$store.getters.appleCount`
doneApple: 'appleCount'
})
3.mapMutations
你可以在组件中使用 this.$store.commit(‘xxx’) 提交 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')`
})
}
}
上面示例直接摘自官方,通过上面demo示例看出,连载荷也可以直接支持,真是很方便
4.mapActoins
和 mapMutations 用法一模一样,换个名字即可。你在组件中使用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')`
})
}
}
如果你想要在组件中调用,直接this.xxx就可以了。
写在最后
本篇对Vuex中的讲述就告一段落了,如果我们用好这些辅助函数,可以让代码更加简化跟容易维护,如有朋友们对此文还有些不理解的地方,欢迎大家指正交流,愿此文能帮到大家,谢谢!