// 負(fù)責(zé)操作localStorage
// 定義localStorage的可以為一個(gè)常量
const KEY ='shopcar';
function getJsonObject(){
var lsSting = localStorage.getItem(KEY);
var list = [];
if(lsSting){
list = JSON.parse(lsSting);
}
return list;
}
// obj格式:{goodsid:87,count:1}
export function setItem(obj){
// 1.0 根據(jù)key獲取localStorage中的已有數(shù)據(jù)
var list = getJsonObject();
// 2.0 將obj 追加到list中
list.push(obj);
// 3.0 將list數(shù)據(jù)轉(zhuǎn)出json字符串存儲(chǔ)到localStorage中
localStorage.setItem(KEY,JSON.stringify(list))
}
// 獲取所有的商品的購買總數(shù)
export function getTotalCount(){
var list = getJsonObject();
// 2.0 計(jì)算總數(shù)
var totalcount = 0;
list.forEach(function(item){
totalcount+=item.count;
})
return totalcount;
}
// 獲取所有商品的id
// 返回的格式: googdsid,goodsid
export function getIdString(){
var list = [];
var obj = getGoodsObj();
for(let key in obj){
list.push(key);
}
return list.join(',');
}
// tmpObj={87:1,90:2};
export function getGoodsObj(){
var tmpObj={};
var list =getJsonObject();
// 2.0 遍歷list 將goodsid的值push進(jìn)入到tmplist
list.forEach(item=>{
if(tmpObj[item.goodsid]){
tmpObj[item.goodsid] += item.count;
}else{
tmpObj[item.goodsid] = item.count
}
});
return tmpObj;
}
// 根據(jù)商品id刪除數(shù)據(jù)
export function removeGoods(goodsid){
// 獲取數(shù)據(jù)
var list = getJsonObject();
var newList=[];
// 刪除list中對(duì)應(yīng)的goodsid的數(shù)據(jù)
list.forEach(item=>{
if(item.goodsid != goodsid){
newList.push(item);
}
});
// 寫入新數(shù)據(jù)
// 3.0 將list數(shù)據(jù)轉(zhuǎn)出json字符串存儲(chǔ)到localStorage中
localStorage.setItem(KEY,JSON.stringify(newList))
}
// 實(shí)現(xiàn)shopnumber.vue組件的自減功能
export function substrictItem(goodsid){
// 獲取數(shù)據(jù)
var list = getJsonObject();
//
// list.forEach((item,index)=>{
// if(item.goodsid != goodsid){
// // 自減邏輯
// if(item.count == 1){
// list.splice(index,1) //由于改變了list的數(shù)量導(dǎo)致forEach會(huì)異常
// }
// }
// });
for(var i = list.length-1;i>=0;i--){
var tmpobj = list[i];
if(tmpobj.goodsid == goodsid){
if(tmpobj.count == 1){
list.splice(i,1);
}else{
list[i].count = list[i].count -1;
}
}
}
// 3.0 將list數(shù)據(jù)轉(zhuǎn)出json字符串存儲(chǔ)到localStorage中
localStorage.setItem(KEY,JSON.stringify(list))
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。