把数组存到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缓存机制。
题外话:有的成长终究是时间换来的~

原创文章 181 获赞 19 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Pandora_417/article/details/105655575
今日推荐