我想知道为什么我更改了数组的特定项目而页面没有更新。我知道 vue.js 的文档指出:
由于 JavaScript 的限制,Vue 无法检测到数组的以下更改:
当您直接使用索引设置项目时,例如vm.items[indexOfItem] = newValue
.
它说我们应该这样做,但我不知道为什么。我发现了一个类似的问题(Vue计算问题-什么时候再次计算) 关于那个。
这是上面问题中的一些代码:
// works well
data() {
return {
cart: {
item: {
nums: 10,
price: 10,
},
},
}
},
computed: {
total() {
return this.cart.item.nums * this.cart.item.price
},
},
methods: {
set() {
//why it worked.
this.cart.item = {
nums: 5,
price: 5,
}
},
},
// oops! not working!
data() {
return {
cart: [
{
nums: 10,
price: 10,
},
],
}
},
computed: {
total() {
return this.cart[0].nums * this.cart[0].price
},
},
methods: {
set() {
this.cart[0] = {
nums: 5,
price: 5,
}
},
},
我对问题的答案感到困惑:
如果出现以下情况,将重新计算总计this.cart
被标记为已更改,this.cart[0]
被标记为已更改或者如果this.cart[0].nums
or this.cart[0].price
被改变了。问题是您正在替换中的对象this.cart[0]
。这意味着this.cart[0].price
并且 nums 不会改变,因为它们仍然指向旧对象。
如果我已经替换了对象this.cart[0]
, why this.cart[0]
没有标记为已更改?为什么this.cart[0].price
and nums
仍然指向旧对象?我已经改变了 this.cart[0]!正确的?
为什么在第一种情况下效果很好?也替换对象。这两种场景有什么区别?