vuex action非同步快取,實現資料快取在state中,減少請求,提高效能
阿新 • • 發佈:2020-12-31
接上一篇
非同步:用action做後端資料的快取
使用步驟:
- 在state中定義一個變數用來做狀態管理
- 取這個變數this.$store.state.xxxx
- 通過
this.$store.dispatch('getComingListAction')
將非同步請求dispatch 到action中 - 到state.js 的actions 中進行非同步請求
- 將介面的資料提交到mutation中
- 在mutation 中將提交來的值賦值給 store 中的變數(狀態)
上程式碼
1.在state中定義一個變數用來做狀態管理
state: { comingList: [] },
2.頁面在 判斷如果store 中的資料沒有的話就 發ajax.有的話就 使用快取的資料
mounted () { /* if(store中的list.length==0) { 發ajaX請求 } else { 使用快取資料 } */ if (this.$store.state.comingList.length === 0) { this.$store.dispatch('getComingListAction') } else { console.log('使用快取資料') } } }
通過 this.$store.dispatch(‘getComingListAction’),將非同步請求dispatch 到action中
3.由於直接在mutation方法中進行非同步操作,將會引起資料失效。所以提供了Actions來專門進行非同步操作,最終提交mutation方法。
到state.js 的actions 中進行非同步請求
Actions中的方法有兩個預設引數
- store上下文(相當於箭頭函式中的this)物件
- data 掛載引數
actions: { // 這裡的store 是vuex 中自動給的引數 getComingListAction (store) { axios({ url: '', headers: {} }).then(res => { store.commit('comingListMutation', res.data.data.films) }).catch(err => { console.log(err) }) } }
store.commit(‘comingListMutation’, res.data.data.films) 提交到 mutations 裡面以後
4.在mutation 中將提交來的值賦值給 store 中的變數(狀態)
mutations: {
comingListMutation (state, data) {
state.comingList = data
}
},
5.頁面中使用this.$store.state.comingList
來接收資料進行遍歷渲染
試試吧!!!