【发布时间】:2019-08-22 18:24:35
【问题描述】:
我想知道为什么我更改了数组的特定项而页面没有更新。我知道 vue.js 的文档指出:
由于 JavaScript 的限制,Vue 无法检测到数组的以下更改:
当您直接使用索引设置项目时,例如
vm.items[indexOfItem] = newValue.
它说我们应该这样做,但我不知道为什么。我发现了一个类似的问题(Vue computed issue - when will it compute again)。
这是上面问题中的一些代码:
// 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或this.cart[0].price已更改,则将重新计算总数。问题是您正在替换this.cart[0]中的对象。这意味着this.cart[0].price和 nums 不会改变,因为它们仍然指向旧对象。
如果我替换了this.cart[0] 中的对象,为什么this.cart[0] 没有标记为已更改?为什么this.cart[0].price 和nums 仍然指向旧对象? 我已更改 this.cart[0]!对吗?
为什么在第一种情况下效果很好? 也替换对象。这两种情况有什么区别?
【问题讨论】:
标签: javascript vue.js