vuex store狀態管理隨筆-技巧

  • store文件目錄預覽

desc:爲了項目更好的維護管理,store狀態也需要進行模塊化管理,shopping、profession代表有兩個不同模塊,例如管理登錄的用戶信息,可以新建一個userInfo來管理

  •  目錄解析

     1、state.js  管理狀態

export default {
    professional:{
        cabinTypes:["Y","S"]
    }

};

組件index.js  computed獲取值

//index.js
export default{
    data(){
    },
    computed:{
        cabinTypes(){
           return  this.$store.state.professional.cabinTypes //獲取到值 ["Y","S"]
        },
    }

}

2、mutation-types.js  【提高代碼耦合性太高,減少硬編碼,團隊開發時,對mutations統一管理,找函數很直觀,可以不使用】

// 專業版顯示/隱藏表頭
export const UPDATE_CABINTYPES= 'UPDATE_CABINTYPES';

3、mutations.js  :更新state值的一些function,mutation 都是同步事務


import * as types from './mutations_types'

export default {
    //更新cabinTypes
    [types.UPDATE_CABINTYPES](state,value) {
      state.professional.cabinTypes= value;
    },
};

組件index.js  updateCabinTypes 方法commit改變state裏cabinTypes,value爲接收到的新參數

//index.js
export default{
    data(){
    },
    computed:{
        cabinTypes(){
           return  this.$store.state.professional.cabinTypes //獲取到值 ["Y","S"]
        },
    },
    methods:{
        updateCabinTypes(){
            this.$store.commit('UPDATE_CABINTYPES',["F","D"]);  
        }
    }

}

4、actions.js  處理異步方法 Action 通過 store.dispatch 方法觸發:


export default {
    // 增加選擇的信息
    add_selected_info: ({ commit }, { info }) => {
        return new Promise((resolve, reject) => {
            commit(types.ADD_SELECTED_INFO, info);
            resolve()
        });
    },
};

組件index.js  add_selected_info方法,info爲接收到的新參數

//index.js
export default{
    data(){
    },
    computed:{
        cabinTypes(){
           return  this.$store.state.professional.cabinTypes //獲取到值 ["Y","S"]
        },
    },
    methods:{
        updateCabinTypes(){
            this.$store.commit('UPDATE_CABINTYPES',["F","D"]);  
        },
        add_selected_info(){
            this.$store.dispatch('add_selected_info',{id:1,name:'產品1'});  
        },
    }

}

5、getters.js 向外部拋出state 中派生出一些狀態【簡單說:加工state狀態】

export default {
	getCabinTypesF(state) {
        return state.professional.cabinTypes.filter(it=>it=='F')
    },

組件index.js 

//index.js
export default{
    data(){
    },
    computed:{
        cabinTypes(){
           return  this.$store.state.professional.cabinTypes //獲取到值 ["Y","S"]
        },
        cabinTypesF(){
           return  this.$store.getters.cabinTypesF //獲取到值 ["F"]
        },
    },
    methods:{
        updateCabinTypes(){
            this.$store.commit('UPDATE_CABINTYPES',["F","D"]);  
        }
    }

}

 

發佈了110 篇原創文章 · 獲贊 38 · 訪問量 43萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章