vue.js - vue 和 vuex:Evrything 工作,只是想看看如何缩短代码。是否有某种观察者或缩短代码的最佳方法是什么?
问题描述
以下是我如何实现购物车的操作。不要真正尝试了解发生了什么,重点是每个函数中的最后一行代码。哪个是
localStorage.setItem('cart', JSON.stringify(state.cart));
这些动作调用突变,其中会改变变量cart
,因此每次更改后我都会将新购物车保存在 localStorage 中。代码有效,但我不喜欢重复。有更好的方法吗?我想可能是观察者改变状态变量?但是有人知道它是否存在吗?以及如何使用它?
export async function removeItemFromCart({state, getters, commit}, id){
let ind = getters.index(id);
commit('removeFromCart', ind);
localStorage.setItem('cart', JSON.stringify(state.cart)); //here
}
export async function setCnt({state, getters, commit, rootGetters}, { id, cnt }){
let ind = getters.index(id);
if(state.cart[ind].cnt + cnt >= 1 && state.cart[ind].cnt + cnt <= rootGetters['watches/item'](id).cnt)
commit('addCnt', { ind, cnt})
localStorage.setItem('cart', JSON.stringify(state.cart)); //here
}
解决方案
我认为最好的方法可能是创建另一个在本地存储中设置购物车的操作。
export async function removeItemFromCart({state, getters, commit}, id){
let ind = getters.index(id);
commit('removeFromCart', ind);
commit('setCart', state.cart);
}
export async function setCnt({state, getters, commit, rootGetters}, { id, cnt }){
let ind = getters.index(id);
if(state.cart[ind].cnt + cnt >= 1 && state.cart[ind].cnt + cnt <= rootGetters['watches/item'](id).cnt)
commit('addCnt', { ind, cnt})
commit('setCart', state.cart);
}
export function setCart({commit}, cart) {
localStorage.setItem('cart', JSON.stringify(cart));
}
推荐阅读
- go - 是否可以让多个 FileServer 处理程序从不同的文件夹返回?
- c - fprintf() 函数无限期地将最后一个条目写入文件,直到我关闭程序
- r - 在正态分布中绘制 p 值(在 R 中)?
- c++ - 如何在 ubuntu 20.04 中安装编译器 g++-4.8.5
- nomad - 运行任何 bash 命令时使用 exec 的 Nomad 作业失败
- algorithm - 为家庭创造一个家务轮
- c++ - 在 Xcode [Mac] 中链接 C++ 库
- python-3.x - 熊猫 3.7 中的 pathlib 连接路径
- git - 开发分支上的 Git 合并功能到另一个已经存在的开发分支
- javascript - Javascript - 如何将 ajax 调用中的数据传递给 3 个函数?