页面使用了store中的数据,当点击加号(减号)时,需要同步修改store里的数据
执行mutations中的changeCartList方法,打印出来数据变化了,但是视图并没有更新
问题:
1、原始代码
mutations: {
changeCartList(state,payload){
const {shopId,productId,productItem,num}=payload
if(state.cartList[shopId]){
if(state.cartList[shopId].productList[productId]){
state.cartList[shopId].productList[productId].count+=num
}else{
const productData={
[productId]:{
...productItem,
count:num
}
}
state.cartList[shopId].productList={...state.cartList[shopId].productList,...productData}
}
}else{
const shopData={
[shopId]:{
productList:{
[productId]:{
...productItem,
count:num
}
}
}
}
state.cartList={...state.cartList,...shopData}
}
if(state.cartList[shopId].productList[productId].count<0){
state.cartList[shopId].productList[productId].count=0
}
console.log(state.cartList[shopId].productList[productId].count);
}
}
2、修改以后的代码(视图更新了)
mutations: {
changeCartList(state,payload){
const {shopId,productId,productItem,num}=payload
let shopInfo=state.cartList[shopId]
if(!shopInfo){
shopInfo={
productList:{
[productId]:{
...productItem,
count:0
}
}
}
}
let productInfo=shopInfo.productList[productId]
if(!productInfo){
productInfo={...productItem,count:0}
}
productInfo.count+=num
shopInfo.productList[productId]=productInfo
state.cartList[shopId]=shopInfo
}
}