購物車之進階版 ...
購物車之進階版
if (this.$store.state.loginState === 'ok') {
let result = { pic, name, sale, proid, flag, num }
if (!localStorage.getItem('cars')) { //1如果觸發時沒有本地數據 就將新創建的對象obj和新創建的lis購物車作為新的放進本地
this.lis.push(result)
this.obj[this.userinfo] = this.lis
localStorage.setItem('cars', JSON.stringify(this.obj))
} else { // 2否則就是有本地 如果有本地 下一步
let dic = JSON.parse(localStorage.getItem('cars'))
if (dic[this.userinfo] !== undefined) { // 2.1如果本地obj[此時的用戶] !==undefined 說明這個用戶里的購物車有數據
this.lis = dic[this.userinfo] //有數據就將老數據賦值給 購物車lis
let flag = false
this.lis.map(item => { // 迴圈老數據,看老數據里的名字與 新添加的 result名字是否有重覆
if (item.name === result.name) { //2.1.1如果有重覆就將老數據的num+1
item.num += 1
flag = true //2.1.2並且給flag賦值true 讓外面的購物車不要添加進去
}
})
if (!flag) { // 2.1.3如果flag等於flase就說明老數據沒有此商品,正常添加
this.lis.push(result)
flag = false
}
dic[this.userinfo] = this.lis // 最後一步 重新賦值給dic對象
localStorage.setItem('cars', JSON.stringify(dic)) //解析
} else {
this.lis.push(result) //2.2如果老數據里沒有這個賬戶。就說明他沒有購物車數據,此時就要重新給他添加數據了
dic[this.userinfo] = this.lis
// dic[this.userinfo] = this.lis
localStorage.setItem('cars', JSON.stringify(dic))
}
}
} else {
this.$router.push('/login')
}
},