关于vuex的...mapActions、 ...mapState、...mapMutations和...mapGetters的理解
关于vuex的…mapActions、 …mapState、…mapMutations和…mapGetters的理解背景:mapState、mapGetters、mapMutations、mapActions他们返回的都是一个对象,而vue的methods、computed也是一个对象。在js中不能把多个对象直接放到一个对象中,如:{{name:‘aaa’},{age:18}}是错的,故而...
背景:
mapState、mapGetters、mapMutations、mapActions他们返回的都是一个对象,而vue的methods、computed也是一个对象。在js中不能把多个对象直接放到一个对象中,如:{{name:‘aaa’},{age:18}}是错的,故而需要特殊的方法处理。
下面,将以mapState为代表详细展示:
首先:我们先回顾一下vue的methods用法:
<script type="text/javascript">
var app=new Vue({
el:'#app',
data:{},
methods:{}
})
</script>
以上是vue的常规定义,我们可以看到methods后接的是一个对象
接下来,我们再看mapState的用法:
第一种:
// vuex 提供了独立的构建工具函数 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
}
})
}
以上vuex官网代码,这里是直接把mapState对象赋给了computed,但是computed的写法并不是computed:{}。其实这里的还是把一个对象赋值给了methods,只是限制了这个对象只能是一个mapState对象。我们都知道在vuex中,computed不单单可以接收mapState对象也可以接收mapGetters对象。当computed要同时接收mapState和mapGetters怎么办呢?
首先、我们不可能为一个vue实例写两个computed,因为后者会覆盖前者。所以只能这样写:
// vuex 提供了独立的构建工具函数 Vuex.mapState
import { mapState } from 'vuex'
export default {
computed: {
mapState({
}),
mapGetters({
})
}
}
只有这样子我们才能保证computed都接收到mapState和mapGetters。但是如果这样进行编译的话就会报错。
所以我们只能用 …mapState 、…mapGetters 。
我们先来看看 … 是什么东东。… 叫做扩展运算符,是es6的知识。具体的解释百度就有了,我理解不深就不误人子弟。反正通过这个 … 可以把多个对象合并成一个对象,再把这个合并好的最终对象传入到computed 属性去。
我们来看看官方文档的解释:
注意,mapState 返回一个对象。我们如何使用 mapState 合并其他局部的计算属性呢?通常地,为了将多个对象合并为一个对象,再把这个合并好的最终对象传入到 computed 属性去,我们不得不使用一个工具函数来实现。然而有了对象扩展运算符(ECMAScript 提案 stage-3),我们可以大大简化语法:
computed: {
localComputed () { /* ... */ },
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
// ...
})
}
来自 https://vuex.vuejs.org/zh/guide/state.html
这就是mapState第二种用法了。
那段编译出错的代码则改成:
// vuex 提供了独立的构建工具函数 Vuex.mapState
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
}),
...mapGetters({
})
}
}
更多推荐
所有评论(0)