[英]VueJS two-way data binding
我想使用 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>
除了计算属性( calcTotal
)之外,您还可以从<input>
监听input
-event的amount
和total
:
<input type="number" v-model="amount" @input="onAmountChange">
<input type="number" v-model="total" @input="onTotalChange">
amount
的<input>
的处理程序将设置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;
}
}
new Vue({ el: '#app', 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; } } })
<script src="https://unpkg.com/vue@2.5.17"></script> <div id="app"> <div>amount: <input type="number" v-model="amount" @input="onAmountChange"></div> <div>price: <input type="number" v-model="price" disabled></div> <div>total: <input type="number" v-model="total" @input="onTotalChange"></div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.