vuex用来全局管理vue数据,树状结构,可以分模块。
vue组件使用vuex中的数据,两种方式
》》》1.注册到根vue实例后,通过 this.$store.state
》》》2.1的方式比较冗余,可以用map映射到当前组件,直接类似使用当前组件的数据和方法
通过全局$store方式 | 通过map映射 | ||
state | 根模块 | this.$store.state.xxx |
computed: { ...mapState(["xxx']); } 或 computed: { ...mapState({ xxxxxx: "xxx" }); } // vue组件 this.xxx 或 this.xxxxxx |
子模块banana |
this.$store.state.banana.xxx |
computed: { ...mapState({ xxxx: state => state.banana.xxx }); } // vue组件 this.xxxx |
|
getter | 根模块 | this.$store.getters.fullname |
computed: { ...mapGetters(["fullname"]) } 或 computed: { ...mapGetters({ fullname: "fullname" }) // vue组件 this.fullname
|
子模块banana | this.$store.getters.bananafullname |
computed: { ...mapGetters(["bananafullname"]) }) 或 computed: { ...mapGetters({ bfullname: "bananafullname" }) } //vue组件 this.bananafullname 或 this.bfullname |
|
mutation | 根模块 |
this.$store.commit("xxx",{...}) 或 this.$store.commit({ type: "xxx", ... }) |
methods: { ...mapMutations(["ageplus"]) } 或 methods: { ...mapMutations({ agePlus: "ageplus" }) } // vue组件 this.ageplus({...}) 或 this.agePlus({...}) |
子模块banana | 同根模块 | 同根模块 | |
action | 根模块 | this.$store.dispatch("xxx") |
methods: { ...mapActions(["xxx"]) } 或 methods: { ...mapActions({ xxx: "xxx" }); // vue组件 this.xxx(); |
子模块banana | 同根组件 | 同根组件 |
getter / mutation / action参数情况(未指定命名空间):
例子 | 参数说明 | |||||||||
getter 相当于computed,映射一些数据
|
根模块 |
getters: { fullname (state,getters,rootState,rootGetters){ return state.firstname+"."+state.lastname; } } |
提供四个参数:
|
|||||||
子模块 |
getters:{ fullname (state,getters,rootState,rootGetters){ ... } } |
提供四个参数
|
||||||||
mutation 修改state中的值,建议只能在这里修改
|
根模块 |
mutations: { setName (state, payload){ state.name = payload.name; } } |
提供两个参数:
|
|||||||
子模块 | ||||||||||
action 一些操作,可以异步
|
根模块 |
actions: { agePlusAsync (context){ context.commit("setName",{name:"xxx"}); } |
提供一个参数:
|
|||||||
子模块 |
同根模块
|
同根模块 |
vuex的getters 和 vue的computed有个共同的特性,改变任意一个值(state / data),其中的方法都会被执行。
vuex在不指定命名空间的情况下,默认会把所有函数(mutations和actions)放在同一个命名空间下面,
如果父子模块的actions或mutations中有相同的函数名,在vue组件中通过 this.$store.dispatch("action函数名") 或 this.$store.commit("mutation函数名") 是会依次执行父子模块的函数。
mutation和action允许父子模块函数名相同,
getters不允许,会报错。