vuex辅助函数的用法是什么?你知道哪些?
发布时间:2022-02-22 13:13:00 所属栏目:语言 来源:互联网
导读:vuex辅助函数的用法是什么?vue中辅助函数有mapState、mapActions、mapMutations等等,对新手来说可能不是很了解vuex辅助函数的使用,因此这篇文章就给大家来介绍一下vuex辅助函数。 mapState import { mapState } from vuex export default { // ... comput
|
vuex辅助函数的用法是什么?vue中辅助函数有mapState、mapActions、mapMutations等等,对新手来说可能不是很了解vuex辅助函数的使用,因此这篇文章就给大家来介绍一下vuex辅助函数。 mapState import { mapState } from 'vuex' export default { // ... computed:{ ...mapState({ // 箭头函数可使代码更简练 count: state => state.count, // 传字符串参数 'count' 等同于 `state => state.count` countAlias: 'count', // 为了能够使用 `this` 获取局部状态,必须使用常规函数 countPlusLocalState (state) { return state.count + this.localCount } }) } } 定义的属性名与state中的名称相同时,可以传入一个数组 //定义state const state={ count:1, } //在组件中使用辅助函数 computed:{ ...mapState(['count']) } mapGetters computed:{ ...mapGetters({ // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount` doneCount: 'doneTodosCount' }) } 当属性名与getters中定义的相同时,可以传入一个数组 computed:{ computed: { // 使用对象展开运算符将 getter 混入 computed 对象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) } } 总结: mapState与mapGetters都用computed来进行映射 在组件中映射完成后,通过this.映射属性名进行使用 mapMutations methods:{ ...mapMutations({ add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')` }) } 当属性名与mapMutatios中定义的相同时,可以传入一个数组 methods:{ ...mapMutations([ 'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')` // `mapMutations` 也支持载荷: 'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)` ]), } mapActios mathods:{ ...mapActions({ add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')` }) } 当属性名与mapActios中定义的相同时,可以传入一个数组 methods:{ ...mapActions([ 'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')` // `mapActions` 也支持载荷: 'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)` ]), } 总结 mapMutations与mapActios都在methods中进行映射 映射之后变成一个方法 多个modules 在不使用辅助函数的时候, this.$store.commit('app/addCount') 使用辅助函数,辅助函数的第一个参数给定命名空间的路径 computed: { ...mapState('some/nested/module', { a: state => state.a, b: state => state.b }) }, methods: { ...mapActions('some/nested/module', [ 'foo', // -> this.foo() 'bar' // -> this.bar() ]) } 或者使用 createNamespacedHelpers函数来创建一个基于命名空间的辅助函数 import { createNamespacedHelpers } from 'vuex' const { mapState, mapActions } = createNamespacedHelpers('some/nested/module') //给定路径 //使用方法与之前相同 export default { computed: { // 在 `some/nested/module` 中查找 ...mapState({ a: state => state.a, b: state => state.b }) }, methods: { // 在 `some/nested/module` 中查找 ...mapActions([ 'foo', 'bar' ]) } } 以上就是关于vuex辅助函数的用法的相关介绍,有需要的朋友可以参考上述代码,希望对大家学习vuex辅助函数有帮助,想要了解更多可以继续浏览其他相关的文章。 (编辑:张家口站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |

