vuex的使用場景
多處需要更改同一個數(shù)據(jù)時,需要使用vuex
舉個例子:購物車商品數(shù)量,在商品列表頁面添加商品會更改這個值,在詳情頁增減商品數(shù)量會更改這個值,進入購物車刪除商品也會更改這個值,通過提交mutation來更改這個值就很簡單明了,如果每次都調(diào)用獲取購物車數(shù)量的接口(前提得有),也能實現(xiàn),但是每一次的HTTP請求,都是對瀏覽器性能消耗。
跨組件共享數(shù)據(jù)、跨頁面共享數(shù)據(jù)
比如loading狀態(tài),在很多頁面都需要使用
vuex 模塊化后如何調(diào)用其他模塊的屬性和方法
actions:{
getListData(context,payload){
console.log(context);
},
}
打印 action 的第一個參數(shù)
- commit 用于調(diào)用mutation,當前模塊和其他模塊;
- dispatch 用于調(diào)用action,當前模塊和其他模塊;
- getters 用于獲取當前模塊getter;
- state 用于獲取當前模塊state;
- rootState 用于獲取其它模塊state;
- rootGetters 用于獲取其他模塊getter;
在一個模塊的actions中調(diào)用其他模塊的actions
dispatch('vip/get', {}, {root: true})
參數(shù)一:是其他模塊的 actions 路徑,。
參數(shù)二:是傳給 actions 的數(shù)據(jù), 如果不需要傳數(shù)據(jù), 也必須預留,
參數(shù)三:是配置選項, 申明這個 acitons 不是當前模塊的
在一個模塊如果想觸發(fā)其他模塊的mutation動態(tài)更新state
commit('vip/receive', data, {root: true})
參數(shù)一:其他模塊的 mutations 路徑
參數(shù)二:傳給 mutations 的數(shù)據(jù), 如果不需要傳數(shù)據(jù), 也必須預留,
參數(shù)三:第三個參數(shù)是配置選項, 申明這個 mutations 不是當前模塊的
在一個模塊需要使用其他模塊的getters
rootGetters['vip/get']
在一個模塊需要使用其他模塊的state
rootState['vip/data']