Vue 中的多个因变量

Multiple dependant variables in Vue

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

例如,我们有一个不能更改的折扣前价格,我们可以:

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

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

是否可以在不必为每个 @input 事件创建单独的处理程序并应用 v-model 指令的情况下完成?

一种选择是使用 v-model 与计算属性的绑定,这样您就可以控制设置逻辑。

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 上使用观察者。在这种情况下,它不会导致无限循环,因为值达到平衡,如果值发生变化,观察者只有 运行。不过,我一般会谨慎使用 co-dependent 观察者。

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

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