把數組存到vuex的state中,並用localStorage長期緩存

數組參數爲cartList
傳參到 actions——>mutations——>state
參數是數組,一定要用JSON.stringify轉換爲字符串格式

detail.vue 傳參

this.$store.dispatch('saveCartList',JSON.stringify(this.detailCart));

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './actions'
Vue.use(Vuex)

const state={
  username:defaultName, //登錄用戶名
  cartCount:0,  //購物車數量
  cartList:[]
}

export default new Vuex.Store({
  state,
  mutations,
  actions
});

store/mutations.js

判斷是否有緩存:
若有緩存,則將緩存通過JSON.parse從string格式轉換爲object格式,再與後面傳過來的數組相結合
且localStorage只能緩存string格式,所以又要將緩存通過JSON.stringify轉爲string格式

saveCartList(state,pro){
    if(localStorage.cartList){
      state.cartList=JSON.parse(localStorage.cartList).concat(JSON.parse(pro))
      localStorage.cartList=JSON.stringify(state.cartList)
    }else{
      state.cartList=state.cartList.concat(JSON.parse(pro))
      localStorage.cartList = JSON.stringify(state.cartList)
    }
  }

store/actions.js

export default{
  saveCartList(context,pro){
    context.commit('saveCartList',pro)
  }
}

接收參數

let pp=this.$store.state.cartList;
console.log(pp)

通過這一大疑難 ,對vuex裏的三個機制有了深刻了解,還有localStorage緩存機制。
題外話:有的成長終究是時間換來的~

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