我想使用Vue的两种数据绑定方式动态更改amount
和total
的值。对于给定的产品,price
是固定的。当用户更改amount
时,将计算total = amount * total
。同样,用户可以输入total
,然后将计算amount = total / price
。此时我迷路了:
var app = new Vue({
el: '#app',
data: {
amount: 1,
price: 100,
},
computed: {
calcTotal: function() {
return this.total =
parseFloat(this.amount) *
parseFloat(this.price)
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
amount: <input v-model="amount"> <br><br> price: <input v-model="price" disabled> <br><br> total: <input v-model="calcTotal"> <br><br>
</div>
答案 0 :(得分:2)
您可以从calcTotal
到<input>
和amount
的{{3}}到listen而不是计算的属性(total
) :
<input type="number" v-model="amount" @input="onAmountChange">
<input type="number" v-model="total" @input="onTotalChange">
amount
的{{1}}的处理程序将设置<input>
的{{1}}的值,反之亦然:
total
<input>
data() {
return {
amount: 0,
total: 0,
price: 100,
}
},
methods: {
onTotalChange(e) {
const total = e.currentTarget.value;
this.amount = total / this.price;
},
onAmountChange(e) {
const amount = e.currentTarget.value;
this.total = amount * this.price;
}
}