vuex學習筆記

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;

  }

}

提供四個參數:

state 全局映射,能夠經過(state.子模塊名.子模塊state名)訪問子模塊數據
getters 在這裏不要調用getters中的當前函數,防止出現死循環
rootState/rootGetters這裏測試和state/getters是同樣的

 

子模塊

getters:{

  fullname (state,getters,rootState,rootGetters){

    ...

  }

}

 提供四個參數

state 局部state
getters 全部的getters數據,包括根模塊和子模塊。getters在整個store模塊體系中是共有的。
rootState 根模塊state,能夠經過(rootState.子模塊名.子模塊屬性名)獲取子模塊屬性
rootGetters 測試和getters是同樣的。

 

mutation

修改state中的值,建議只能在這裏修改

 

根模塊

mutations: {

  setName (state, payload){

    state.name = payload.name;

  }

}

 提供兩個參數:

 

state 全局映射,能夠經過state.banana.firstname訪問子模塊屬性
payload 負載信息。vue組件中this.$store.commit("setName",{name:"xxx"})或this.$store.commit({type:"setName",name:"xxx"})自動對應對象{name:"xxx"}

 

子模塊    

action

一些操做,能夠異步

 

根模塊

 actions: {

  agePlusAsync (context){

    context.commit("setName",{name:"xxx"});

}

 提供一個參數:

 

context 上下文對象,包括 state / rootState / getters / rootGetters / commit / dispatch 6個屬性

 

子模塊

 同根模塊

 

 同根模塊

 

 vuex的getters 和 vue的computed有個共同的特性,改變任意一個值(state / data),其中的方法都會被執行。

 

vuex在不指定命名空間的狀況下,默認會把全部函數(mutations和actions)放在同一個命名空間下面,

  若是父子模塊的actions或mutations中有相同的函數名,在vue組件中經過 this.$store.dispatch("action函數名") 或 this.$store.commit("mutation函數名")  是會依次執行父子模塊的函數。

  mutation和action容許父子模塊函數名相同,

  getters不容許,會報錯。

相關文章
相關標籤/搜索