Vuex 使用筆記

 

在使用Vuex之前需要使用Vue聲明組件 

  1. Vue.use(Vuex)
  2. let store = new Vuex.store({
  3.     state,// Vuex中保存數據 
  4.     mutations, // 對Vuex中的state中的數據進行操作 
  5.     actions, //使用 commit() 對mutations操作
  6.     getters //類似於computed計算屬性 
  7. })
  8. new Vue({ store })

需要使用在Vue中綁定 store
Store聲明之後回創建一個 $store對象  $store對象中有 Vuex中的state對象 以及 getter對象 可通過$store.state 或者$store.getter 的方法調用
actions對象 需要通過dispatch方法調用 如 
methods:{
        add(){ dispatch("addcount","可以傳輸的數據") }
}
vuex中的actions 對象
let actions = {   
    addcount({commit,state},val){  
        commit( "addcounts",val )  
    }  
}
Vuex中的mutations 對象
let mutations = {
    addcounts(state,val){ // 
        state.count += val
    }
}
Vuex中的state 對象 
let state = {
    count:0,
}

Vuex中的getters對象 使用方法 
let getters = {
    decrement(state){
        state.count
    }

調用在對應vue組件中
  computed:{
       dec(){
           return this.$store.getters.decrement; //在getters中定義的函數不需要調用 因爲爲getter方法 在數據讀取時會自動調用
       }
  }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章