Vue中的多个因变量

问题描述

实现相互依赖的多个可变变量的最简单方法是什么?

例如,我们的折扣前价格无法更改,我们可以:

  1. 应用折扣,折扣后的价格应更新,
  2. 或在折扣后更改价格,折扣应相应更新。

对于此示例,我提出了以下解决方案:https://jsfiddle.net/2wh6cgq5/1/

是否可以不必为每个@input事件创建单独的处理程序并应用v-model指令来做到这一点?

解决方法

一种选择是将v模型绑定与计算出的属性一起使用,以便您可以控制设置逻辑。

new Vue({
  el: '#app',data: {
    priceBeforeDiscount: 100,discount: 50,priceAfterDiscount: 50,},computed: {
    priceAfterDiscountInput: {
      get() {
        return this.priceAfterDiscount;
      },set(val) {
        this.priceAfterDiscount = val;
        this.discount = this.priceBeforeDiscount - this.priceAfterDiscount;
      }
    },discountInput: {
      get() {
        return this.discount;
      },set(val) {
        this.discount = val;
        this.priceAfterDiscount = this.priceBeforeDiscount - this.discount;
      }
    }
  },})

另一种可能性是在discountpriceAfterDiscount上使用观察者。在这种情况下,它不会导致无限循环,因为值达到平衡,并且观察者仅在值更改时运行。不过,在一般情况下,我会谨慎使用依赖依赖的观察程序。

new Vue({
  el: '#app',watch: {
    discount() {
        this.priceAfterDiscount = this.priceBeforeDiscount - this.discount;
    },priceAfterDiscount() {
        this.discount = this.priceBeforeDiscount - this.priceAfterDiscount;
    }
  },})

但是,我真的不认为您的解决方案有问题。如果不需要使用v-model指令(例如,用于vee-validate),我将其转换为v-bind并在输入处理程序中进行赋值。