老师,我想问一个问题

来源:11-3 Vuex中购物车数据结构的设计(2)

目訫

2021-03-19

老师,如果是正常对象引用的话

let shop = {}
let a = shop
a.id = 11
console.log(shop.id) // 11

如果是响应式引用的话

let shop = reactive({})
let a = shop
a.id = 11
console.log(shop.id) // 11

现在a和shop的引用地址应该一样

但是

为什么在状态管理应用中不是这样

const { shopid, productId, productInfo } = payload
let shopInfo = state.cartList[shopid]
if (!shopInfo) shopInfo = {}
let product = shopInfo[productId]
if (!product) {
    product = productInfo
    product.count = 0
}
product.count += 1
shopInfo[productId] = product
state.cartList[shopid] = shopInfo

如果不写最后一句话state.cartList[shopid] = shopInfo,为什么state里面的cartList没有变化呢

写回答

1回答

Dell

2021-03-19

补充锌改变cartList[shopid],不会触发响应式的处理逻辑,所以页面不会渲染。

0
3
慕后端1194360
addItemToCart: (state, payload) => { const { shopId, productId, product } = payload console.log(shopId, state.cartList[shopId]) // let shopInfo = state.cartList[shopId] if (!state.cartList[shopId]) { state.cartList[shopId] = {} } // let productInfo = state.cartList[shopId][productId] if (!state.cartList[shopId][productId]) { state.cartList[shopId][productId] = product state.cartList[shopId][productId].count = 0 } state.cartList[shopId][productId].count += 1 // shopInfo[productId] = productInfo // state.cartList[shopId] = shopInfo console.log(shopId, state.cartList[shopId]) } 要是直接再该对象上做处理,就正常了。使用let引用,处理数据 let shop = {} let a = shop a.id = 11 console.log(shop.id) // 11 有啥不一样了呢,疑问!!
2022-06-24
共3条回复

Vue3入门与项目实战 掌握完整知识体系

明星讲师DELL亲授,全方位知识点+高匹配度项目,入门到深度掌握

3382 学习 · 1454 问题

查看课程