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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值