state里面的数据在使用的时候,一般是挂在computed里面的,因为如果你挂在data上面,只会赋值一次,不会跟着vuex里面的变化而同步变化,当然也可以通过watch $store去解决这个问题,如下:
computed: {
hasBg(){
return this.$store.state.hasBg
}
}
有了vuex,我们不必在考虑组件之间的传值,直接就可以通过$store来获取不同的数据,这样写就太啰嗦了,我们可以将它定义在computed中:
<template>
<div class="home">
{{nickname}}
</div>
</template>
<script>
export default {
name: 'home',
computed:{
nickname(){
return this.$store.state.nickname
}
}
}
</script>
但是当要获取多个store中的数据的时候,computed中的代码量仍旧会偏大。因此有了mapState:
import {mapState} from 'vuex'
export default {
name: 'home',
computed: mapState(['nickname','age','gender'])
}
mapState(['nickname','age','gender']) //映射哪些字段就填入哪些字段
等价于:
nickname(){return this.$store.state.nickname}
age(){return this.$store.state.age}
gender(){return this.$store.state.gender}
注意:用mapState等这种辅助函数的时候,前面的方法名和获取的属性名是一致的。
...展开运算符就是为了使用的时候可以更加方便。