使用vuex的mapState是为了获取state的映射关系的,在不使用mapState时候,采用computed中加入全局状态变量的方法如下:
computed: {
count () {
return this.$store.state.count
}
}
但是当组件中需要多个全局状态变量的时候,就很麻烦 使用mapState就可以快速建立映射关系:
方式1:数组
import { mapState } from 'vuex'
const Counter = {
template: `<div>{{ count }}</div>`,
computed: mapState([
// 映射 this.count 为 store.state.count 数组的方式
'count'
])
}
方式二:采用函数(但是注意如果想要使用data中的变量,必须是常规函数而不能是箭头函数)
computed: mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})
方式三:扩展运算符(这种方式比较常用,不仅可以添加新的计算属性,而且可以随意映射state变量而且可以使用局部变量 this.localCount)
computed: {
localComputed () { /* ... */ },
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
// ...
count: state => state.count,
countAlias: 'count',
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}