vuex数据持久化
-
vux代码
import Vue from 'vue' import Vuex from 'vuex' // 加载vuex组件 Vue.use(Vuex) let store = new Vuex.Store({ state: { // 变量存储库 token: "", // 购物车商品信息 // 如果localStorage里有数据就提取出来并且json反解析成数组里嵌套对象 如果没有就是空数组 cartarry: JSON.parse(localStorage.getItem("cartattr")) || [], }, mutations: { // 同步的方法 // 第一个参数必须是state, 第二个参数是外面要存进去的值 // 设置vuex的token setToken(state, token){ state.token = token }, // 添加商品到购物车 tocart(state, tag){ // 查询出v.title==tag.label的所有对象 let goods = state.cartarry.find(v=>v.title==tag.label); if (goods){ goods.cartCount += 1; }else { state.cartarry.push({title: tag.label, cartCount: 1}) } }, // 购物车数量+1 addCart(state, index){ state.cartarry[index].cartCount += 1; }, // 购物车数量-1 removeCart(state, index){ if (state.cartarry[index].cartCount > 1){ state.cartarry[index].cartCount -= 1; }else { // window.confirm("确定从购物车移除商品吗?") 弹窗显示这些字, 点击确定就为true 点击取消就为false if (window.confirm("确定从购物车移除商品吗?")){ state.cartarry.splice(index, 1); } } }, // 清空购物车 clearCart(state){ state.cartarry = [] } }, actions: { // 异步的方法 }, getters: { // 计算方法 计算属性 相当于vue的computed totalCount: state=>{ let num = 0; state.cartarry.forEach(v => { num += v.cartCount; }); return num; } } }) // 监听每次调用mutations的时候, 都会进这个方法, 然后我们可以做一些自己想做的处理 store.subscribe((mutations, state)=>{ localStorage.setItem("cartattr", JSON.stringify(state.cartarry)); }) export default store
-
接受vux返回的对象
-
借助本地存储localStorage
-
把vuex的属性值动态化
-
抛出vux