vuex的辅助函数
Vuex提供了一些方便的辅助函数,可以简化我们在组件中使用store的代码。以下是一些常用的辅助函数:
- mapState:将store的state映射为组件的计算属性,可以直接使用state中的数据。
import { mapState } from 'vuex'
export default {
computed: {
...mapState([
'count'
])
}
}
- mapGetters:将store的getters映射为组件的计算属性,可以直接使用getters中的数据。
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters([
'doneTodos'
])
}
}
- mapMutations:将store的mutations映射为组件的methods,可以直接调用mutations中的方法。
import { mapMutations } from 'vuex'
export default {
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
])
}
}
- mapActions:将store的actions映射为组件的methods,可以直接调用actions中的方法。
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions([
'incrementAsync', // 将 `this.incrementAsync()` 映射为 `this.$store.dispatch('incrementAsync')`
])
}
}
原文地址: https://www.cveoy.top/t/topic/ICx 著作权归作者所有。请勿转载和采集!