当computed需要获取多个state状态时,将这些状态都声明为计算属性会有些重复和冗余
let state = {
count: 5
name :'帅哥' ,
sex:'男',
from :"china"
}
export default state
<script>
export default {
data () {
return {
dataCount: this.$store.state.count
}
},
computed:{
count(){
return this.$store.state.count
},
name(){
return this.$store.state.name
},
sex(){
return this.$store.state.sex
}
}
</script>1.mapstate
当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键:
首先引入
import { mapState } from 'vuex'然后使用
<script>
export default {
data () {
return {
dataCount: this.$store.state.count}
},
computed:mapState({ count:"count", name::"name", sex:"sex"})
</script>和上面的是一样的效果
console(mapstate)
//{ count:"count",name::"name",sex:"sex"}computed接收mapstate的返回值,是一个对象
2...mapstate
mapstate
函数返回的是一个对象。我们如何将它与局部计算属性混合使用呢?例如
let a={
b:“我是b”,
mapstate
}
console(a)
//{b:“我是b”,{count:"count",name::"name",sex:"sex"}}是这样的效果利用展开运算符...将它与局部计算属性混合使用
let a={
b:“我是b”,
...mapstate
}
console(a)
//{b:“我是b”,count:"count",name::"name",sex:"sex"}
这里的a可以成功将mapState return的json格式,和a自带的b属性成功融合成一个新的对象我也是一个前端新手,有不对的地方欢迎指出