今天小编给大家分享一下Vuex辅助函数如何用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。mapStateimport&nb
今天小编给大家分享一下Vuex辅助函数如何用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
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中的名称相同时,可以传入一个数组
//定义stateconst state={ count:1,}//在组件中使用辅助函数computed:{ ...mapState(['count'])}
computed:{ ...mapGetters({ // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount` doneCount: 'doneTodosCount' })}
当属性名与getters中定义的相同时,可以传入一个数组
computed:{ computed: { // 使用对象展开运算符将 getter 混入 computed 对象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) }}
总结:
mapState与mapGetters都用computed来进行映射
在组件中映射完成后,通过this.映射属性名进行使用
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)` ]),}
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中进行映射
映射之后变成一个方法
在不使用辅助函数的时候,
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辅助函数如何用”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注编程网精选频道。
--结束END--
本文标题: vuex辅助函数如何用
本文链接: https://www.lsjlt.com/news/345853.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0