vuex用來全局管理vue數據,樹狀結構,能夠分模塊。vue
vue組件使用vuex中的數據,兩種方式vuex
》》》1.註冊到根vue實例後,經過 this.$store.state異步
》》》2.1的方式比較冗餘,能夠用map映射到當前組件,直接相似使用當前組件的數據和方法函數
經過全局$store方式 | 經過map映射 | ||
state | 根模塊 | this.$store.state.xxx | computed: {測試 ...mapState(["xxx']);this }spa 或對象 computed: {get ...mapState({it 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不容許,會報錯。