问题所在
我有一个包含多个对象的"products“数组。每个产品对象都包含“价格”属性。我想要观察每个产品中的这个属性是否有可能的变化。当用户在输入框中更改价格时,我使用它来计算佣金价格。
我的产品数组看起来像这样;
[
0: {
name: ...,
price: ...,
commission: ...,
},
1: {
name: ...,
price: ...,
commission: ...,
},
2: {
name: ...,
price: ...,
commission: ...,
},
...
...
...
]
我的代码
我已经试过了,但它没有检测到任何变化,除了第一次加载产品的时候;
watch : {
// Watch for changes in the product price, in order to calculate final price with commission
'products.price': {
handler: function (after, before) {
console.log('The price changed!');
},
deep : true
}
},
产品是这样装入的;
mounted: async function () {
this.products = await this.apiRequest('event/1/products').then(function (products) {
// Attach reactive properties 'delete' & 'chosen' to all products so these can be toggled in real time
for (let product of products) {
console.log(product.absorb);
Vue.set(product, 'delete', false);
Vue.set(product, 'chosen', product.absorb);
}
console.log(products);
return products;
})
}
我已经看过的其他问题,Vue.js watching deep properties,这个问题是试图观察一个还不存在的属性。VueJs watching deep changes in object此组件正在监视另一个组件中的更改。
发布于 2019-06-13 07:24:50
你不能真正深入观察products.price
,因为价格是单个产品的属性,而不是产品数组。
声明性监视器在数组中是有问题的,如果您尝试在监视表达式中使用索引,例如products[0].price
,您将收到来自Vue的警告
Vue警告:无法查看路径:“products.price”。Watcher只接受简单的点分隔路径。若要进行完全控制,请改用函数。
这意味着您可以将programmatic watch与函数一起使用,但它并没有得到很好的解释。
在您的场景中有一种方法可以做到这一点
<script>
export default {
name: "Products",
data() {
return {
products: []
};
},
mounted: async function() {
this.products = await this.apiRequest('event/1/products')...
console.log("After assigning to this.products", this.products);
// Add watchers here, using a common handler
this.products.forEach(p => this.$watch(() => p.price, this.onPriceChanged) );
// Simulate a change
setTimeout(() => {
console.log("Changing price");
this.products[0].price= 100;
}, 1000);
},
methods: {
onPriceChanged(after, before) {
console.log(before, after);
}
}
};
</script>
下面是我的测试Codesandbox (我使用颜色而不是价格,因为测试api中没有价格)
https://stackoverflow.com/questions/56566548
复制相似问题