四种辅助函数
- mapState::返回一个对象,当一个组件需要获取多个状态的时候,使用辅助函数生成计算属性,减少代码量
import { mapState } from 'vuex'
export default {
computed: mapState({
count: state => state.count
count: 'count'
count() {
return state.count + this.localCount
}
})
computed: mapState(['count'])
computed: {
localComputed(){},
...mapState({})
}
}
- mapGetters:仅仅是将store中的getter映射到局部计算属性
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['count'])
...mapGetters({
newCount: 'count'
})
}
}
- mapMutations:将组件中的methods映射为this.$store.commit()调用
import { mapMutations } from 'vuex'
export default {
methods: {
...mapMutations(['increment'])
...mapMutations({
add: 'increment'
})
}
}
- mapActions:将组件中的methods映射为this.$store.dispath()调用
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions(['increment'])
...mapActions({
add: 'increment'
})
}
}
actions: {
actionA({commit, disptach}, data) {
return new Promise((res, rej) => {
setTimeout(() => {
console.log('aaaa')
}, 1000)
})
},
async actionB({commit, dispatch}, data) {
await dispatch('actionA')
console.log('bbbb')
}
}