时间:2023-03-09 12:09:26 | 栏目:vue | 点击:次

在我的不断尝试中,成功的发现了,vuex其实有一个辅助函数map可以解决这个问题,下面就把我总结到的语法分享给大家啦~希望可以帮到你
// 1. 导入辅助函数mapState,它是在vuex中定义的一个工具函数。
// es6 按需导入 import { mapState } from 'vuex'
import { mapState } from 'vuex'
computed: {
// 说明1: ...对象 是把对象展开,合并到computed
// 说明2: mapState是一个函数
// ['数据项1', '数据项2']
...mapState(['xxx']),
...mapState({'新名字': 'xxx'})
}
script: this.xxx
模板: {{xxx}}
图示:

辅助函数mapState对数据重命名
...mapState({'新名字': 'xxx'})
## Vuex-map函数用法汇总

computed: {
// 省略其他计算属性
...mapState(['xxx']),
...mapState({'新名字': 'xxx'})
}
图示

this.$store.state.模块名.xxx;computed: {
...mapState('模块名', ['xxx']),
...mapState('模块名', {'新名字': 'xxx'})
}
使用全局getters
this.$store.getters.xxxcomputed: {
...mapGetters(['xxx']),
...mapGetters({'新名字': 'xxx'})
}
使用modules中的getters
this.$store.getters.模块名.xxxcomputed: {
...mapGetters('模块名', ['xxx']),
...mapGetters('模块名',{'新名字': 'xxx'})
}
使用全局mutations
this.$store.commit('mutation名', 参数)methods: {
...mapMutations(['mutation名']),
...mapMutations({'新名字': 'mutation名'})
}
使用modules中的mutations(namespaced:true)
this.$store.commit('模块名/mutation名', 参数)methods: {
...mapMutations('模块名', ['xxx']),
...mapMutations('模块名',{'新名字': 'xxx'})
}
使用全局actions
this.$store.dispatch('action名', 参数)methods: {
...mapActions(['actions名']),
...mapActions({'新名字': 'actions名'})
}
使用modules中的actions(namespaced:true)
this.$store.dispatch('模块名/action名', 参数)methods: {
...mapActions('模块名', ['xxx']),
...mapActions('模块名',{'新名字': 'xxx'})
}
- 如果namespaced为true,则需要额外去补充模块名
- 如果namespaced为false,则不需要额外补充模块名
