vuex和localStorage实现购物车的长期保存@帅名

mac2025-02-16  7

1.首先简单封装一个localStorage()方法:

const storage = { set(key, value){ // 调用这个方法时候传入一个 key 和 value // 将传入的 value 转换成JSON 字符串 localStorage.setItem(key,JSON.stringify(value)) }, get(key){ // get 方法 直接传入 key 就行 // 反序列化,将 JSON 字符串转换成 JSON 对象 return JSON.parse(localStorage.getItem(key)||'[]') }, remove(){ // 删除 localStorage.removeItem(key) } } export default storage // 将 storage 暴露出去

2.在vuex的store文件中引入,下面就能够使用了

import localStore from '../storage/index.js'

3.将组件中传给store的数据存入localStorage中

在加入购物车组件中传给store商品信息 this.$store.commit("add",obj) store接收 state: { //数据默认设置为localStorage中的数据 storeLs: localStore.get('list') || '' }, add (state, obj) { //此处是为了解决重复添加问题,可无视 let arrLs = state.storeLs.find(v => v.info.id === obj.info.id) if (arrLs) { arrLs.num += obj.num } else { //接收到的数据添到storeLs中 state.storeLs.push(obj) } //将数据存入本地 localStore.set('list', state.storeLs) }

4.购物车页面渲染

//拿到store库中的数组,用shopList就可以直接渲染啦 computed: { shopList(){ return this.$store.state.storeLs } }

5.如果想要存贮,多选框的状态,加减后的数量等,需要深度监听vuex里的数据

watch: { shopList:{ handler(){ localStore.set("list",this.shopList) }, deep:true } } -------------*勤学如春起之苗,不见其增,日有所长*
最新回复(0)