辅助函数 map
辅助函数 map 来使用公共数据,使代码更精简
怎么做
传统形式(this.$store)
export default {
name: 'index',
data() {
return {
num: 0
}
},
computed: {
count() {
return this.store.state.count
},
doubleCount() {
return this.store.getters.doubleCount
}
},
methods: {
// 自增1
increment() {
this.store.commit('increment')
},
// 加指定的值
addForNum() {
this.store.commit('addForNum', { num: this.num })
},
// 异步加1
asyncAdd() {
this.$store.dispatch('asyncAddAction')
}
}
}
使用 map 辅助函数
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
name: 'index',
data() {
return {
num: 0,
localCount: 10
}
},
computed: {
// 【对象形式】
...mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
// 使用这种方式可以更简洁地为state生成的计算属性定义一个别名
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState(state) {
return state.count + this.localCount
}
}),
...mapState([
// 映射 this.count 为 store.state.count
'count'
]),
// 【对象形式】
// 如果你想将一个 getter 属性另取一个名字,使用对象形式
...mapGetters({
// 把 `this.doubleCountAlias` 映射为 `this.store.getters.doubleCount`
doubleCountAlias: 'doubleCount'
}),
// 【数组形式】
...mapGetters(['doubleCount'])
},
methods: {
// 【传统形式】
// 自增1
// increment () {
// this.store.commit('increment')
// },
// // 加指定的值
// incrementBy (amount) {
// this.store.commit('incrementBy', amount)
// },
// 【数组形式】
...mapMutations(['increment', 'incrementBy']),
// 【对象形式】
...mapMutations({
add: 'increment'
}),
// 异步加1
// asyncAdd () {
// this.store.dispatch('asyncAddAction')
// }
// 【数组形式】
...mapActions([
'asyncAddAction' // 将 `this.asyncAddAction()` 映射为 `this.store.dispatch('asyncAddAction')`
]),
// 【对象形式】
...mapActions({
asyncAdd: 'asyncAddAction' // 将 `this.asyncAdd()` 映射为 `this.$store.dispatch('asyncAddAction')`
})
}
}