Vuex-辅助函数mapState来使用公共数据
当访问某个数据项嵌套太深了,用mapState把公共数据(vuex.store) 映射 到本组件内部的计算属性中
mapState的使用步骤
映射
// 1. 导入辅助函数mapState,它是在vuex中定义的一个工具函数。
// es6 按需导入 import { mapState } from 'vuex'
import { mapState } from 'vuex'
computed: {
// 说明1: ...对象 是把对象展开,合并到computed
// 说明2: mapState是一个函数
// ['数据项1', '数据项2']
...mapState(['xxx']),
...mapState({'新名字': 'xxx'})
}
使用
this.xxx
{{xxx}}
示例
// 步骤
// 1. 导入辅助函数mapState,它是在vuex中定义的一个工具函数。
// es6 按需导入 import { mapState } from 'vuex'
import { mapState } from 'vuex'
// 2. 在computed中使用 ...mapState(['books'])
// const res = mapState(['books'])
// res的结果是一个对象: { books: function() {}}
// console.log('mapState', res)
export default {
computed: {
c1 () {
return 'c1'
},
// books: function() {}
// ..res: 把res这个对象合并到computed对象中
// ...res
...mapState(['books'])
}
}
</script>
小结
- mapState是辅助函数,将vuex中的数据投射到组件内部;
- computed:{ …mapState() } 这里的…是对象的展开运算符,整体来看是对象的合并。
Vuex-辅助函数mapState对数据重命名
格式
...mapState({'新名字': 'xxx'})
Vuex-map函数用法汇总
如何使用全局state
● 直接使用: this.$store.state.xxx;
● map辅助函数:
computed: {
// 省略其他计算属性
...mapState(['xxx']),
...mapState({'新名字': 'xxx'})
}
如何使用modules中的state
● 直接使用: this.$store.state.模块名.xxx;
● map辅助函数:
computed: {
...mapState('模块名', ['xxx']),
...mapState('模块名', {'新名字': 'xxx'})
}
如何使用全局getters
● 直接使用:this.$store.getters.xxx
● map辅助函数:
computed: {
...mapGetters(['xxx']),
...mapGetters({'新名字': 'xxx'})
}
如何使用modules中的getters
● 直接使用: this.$store.getters.模块名.xxx
● map辅助函数:
computed: {
...mapGetters('模块名', ['xxx']),
...mapGetters('模块名',{'新名字': 'xxx'})
}
如何使用全局mutations
● 直接使用:this.$store.commit(‘mutation名’, 参数)
● map辅助函数:
methods: {
...mapMutations(['mutation名']),
...mapMutations({'新名字': 'mutation名'})
}
如何使用modules中的mutations(namespaced:true)
● 直接使用: this.$store.commit(‘模块名/mutation名’, 参数)
● map辅助函数:
methods: {
...mapMutations('模块名', ['xxx']),
...mapMutations('模块名',{'新名字': 'xxx'})
}
如何使用全局actions
● 直接使用:this.$store.dispatch(‘action名’, 参数)
● map辅助函数:
methods: {
...mapActions(['actions名']),
...mapActions({'新名字': 'actions名'})
}
如何使用modules中的actions(namespaced:true)
● 直接使用: this.$store.dispatch(‘模块名/action名’, 参数)
● map辅助函数:
methods: {
...mapActions('模块名', ['xxx']),
...mapActions('模块名',{'新名字': 'xxx'})
}