VueJS双向数据绑定绑定

时间:2018-10-01 17:05:37

标签: javascript vue.js vuejs2

我想使用Vue的两种数据绑定方式动态更改amounttotal的值。对于给定的产品,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>

1 个答案:

答案 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;
    }
  }