1. 程式人生 > 其它 >vuex action非同步快取,實現資料快取在state中,減少請求,提高效能

vuex action非同步快取,實現資料快取在state中,減少請求,提高效能

技術標籤:vuevue.js

接上一篇
非同步:用action做後端資料的快取

使用步驟:

  1. 在state中定義一個變數用來做狀態管理
  2. 取這個變數this.$store.state.xxxx
  3. 通過this.$store.dispatch('getComingListAction')將非同步請求dispatch 到action中
  4. 到state.js 的actions 中進行非同步請求
  5. 將介面的資料提交到mutation中
  6. 在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來接收資料進行遍歷渲染
在這裡插入圖片描述
試試吧!!!