mapState使用公共数据
将
state
中的变量映射到当前的组件中使⽤
⽤mapState把公共数据(vuex.store) 映射 到本组件内部的计算属性中
映射
// 1. 导⼊辅助函数mapState,它是在vuex中定义的⼀个⼯具函数。
// es6 按需导⼊ import { mapState } from 'vuex'
import { mapState } from 'vuex'
computed: {
// 说明1: ...对象 是把对象展开,合并到computed
// 说明2: mapState是⼀个函数
// ['数据项1', '数据项2']
...mapState(['xxx']),
...mapState({'新名字': 'xxx'})
}
使用
js中使用:this.xxx
模板上使用:{{xxx}}
直接使用的话 : this.$store.state.xxx
computed: {
...mapState(['xxx']),
...mapState({'新名字': 'xxx'})
}
如何使用modules中的state
直接使用: this.$store.state.模块名.xxx;
computed: {
...mapState('模块名', ['xxx']),
...mapState('模块名', {'新名字': 'xxx'})
}
mapGetters
直接使用:
this.$store.getters.xxx
computed: {
...mapGetters(['xxx']),
...mapGetters({'新名字': 'xxx'})
}
如何使用modules中的getters
直接使用:
this.$store.getters.模块名.xxx
computed: {
...mapGetters('模块名', ['xxx']),
...mapGetters('模块名',{'新名字': 'xxx'})
}
mapMutations
直接使用:
this.$store.commit('mutation名', 参数)
methods: {
...mapMutations(['mutation名']),
...mapMutations({'新名字': 'mutation名'})
}
如何使用modules中的mutations(namespaced:true)
直接使用:
this.$store.commit('模块名/mutation名', 参数)
methods: {
...mapMutations('模块名', ['xxx']),
...mapMutations('模块名',{'新名字': 'xxx'})
}
mapActions
直接使用:
this.$store.dispatch('action名', 参数)
methods: {
...mapActions(['actions名']),
...mapActions({'新名字': 'actions名'})
}
如何使用modules中的actions(namespaced:true)
直接使用:
this.$store.dispatch('模块名/action名', 参数)
methods: {
...mapActions('模块名', ['xxx']),
...mapActions('模块名',{'新名字': 'xxx'})
}
map函数用法汇总
actions和mutations和state的关系图