Jor*_*tte 3 watch vue.js computed-properties vuejs2
我正在从事一个项目,类似于账单经理,所以我希望每次数量或单位值发生变化时都重新计算小计,我已经尝试并搜索使用观察者或计算属性来完成此操作,但我没有找到正确的方法,因为我需要在另一个更改时访问元素的整个范围,就像这样。
模型结构:
所以我认为我应该能够做这样的事情:
Vue.component('item', {
template: '#item',
props: {
item: Object,
},
computed:{
total: function(){
return this.quantity*this.unit_value;
}
},
watch:{
'item.quantity':()=>{
this.subtotal = this.quantity*this.unit_value;
}
}
});
Run Code Online (Sandbox Code Playgroud)
我从列表中读取了几个组件
我使用观察者合并了该方法并在相同的代码中计算以使其更短。
问题是我还没有找到从内部访问孔元素的方法,任何人都可以解释正确的方法吗?谢谢
你不应该在那里使用箭头函数,使用方法声明。
如果要监视item对象的属性,则必须监视item对象本身,并另外使用deep: true监视者的标志。
最后的细节,您正在使用多个未在您的data. 声明它们,否则它们不会是reactive的,即当它们改变时计算不会重新计算。
见代码:
Vue.component('item', {
template: '#item',
props: {
item: Object,
},
data() {
return {
subtotal: null, // added data properties
quantity: null,
unit_value: null
}
},
computed: {
total: function() {
return this.quantity * this.unit_value;
}
},
watch: {
item: { // watching for item now
deep: true, // using deep: true
handler() { // and NOT using arrow functions
this.subtotal = this.quantity * this.unit_value;
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2718 次 |
| 最近记录: |