Vuex 辅助函数:简化组件中 Store 的使用
Vuex 提供了一些辅助函数,可以简化在组件中使用 store 的代码。下面是常用的几个辅助函数:
- 'mapState':将 store 中的 state 映射到组件的计算属性中。
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
count: state => state.count
})
}
}
- 'mapGetters':将 store 中的 getters 映射到组件的计算属性中。
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters([
'doneTodosCount'
])
}
}
- 'mapMutations':将 store 中的 mutations 映射到组件的方法中。
import { mapMutations } from 'vuex'
export default {
methods: {
...mapMutations([
'increment',
'decrement'
])
}
}
- 'mapActions':将 store 中的 actions 映射到组件的方法中。
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions([
'incrementAsync',
'decrementAsync'
])
}
}
使用辅助函数可以使代码更加简洁,同时也方便了开发者的使用。
原文地址: http://www.cveoy.top/t/topic/lZDb 著作权归作者所有。请勿转载和采集!