【问题标题】:Update one field when the other changes - Vue当另一个字段发生变化时更新一个字段 - Vue
【发布时间】:2021-01-15 12:06:54
【问题描述】:

我正在尝试创建一个双向计算器,我选择使用英寸到毫米作为示例。

在此处查看沙盒:https://q8y4s.csb.app/

<template>
  <div>
    <input type="number" v-model="inches" placeholder="Inches" />
    <br />
    <input type="number" v-model="mm" placeholder="Millimeters" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      inches: "",
      mm: "",
    };
  },
  watch: {
    inches: function (newVal) {
      this.mm = newVal * 25.4;
    },
    mm: function (newVal) {
      this.inches = newVal / 25.4;
    },
  },
};
</script>

问题从毫米到英寸。我不完全确定发生了什么,但它似乎是某种反馈循环。我知道我可以使用计算来实现此特定功能,但我更喜欢使用观察者,因为我的项目中的“观察”字段有更多逻辑。

这个tutorial 使用米到公里并完成同样的事情,但我不确定为什么毫米到英寸会产生“反馈循环”效应

【问题讨论】:

  • 当您从 25.4 更改为 4 时,它可以工作,这表明 JS 存在浮点数问题。您可能想研究计算的 getter 和 setter 而不是观察者。
  • 如果是 JS 的问题,是不是计算属性也会发生?
  • 当您使用计算的 getter 和 setter 时,您可以避免陷入无限递归。您的问题是,在使用观察者时,返回的值总是有点偏离而不是严格等价,这会导致观察者修改彼此的观察值,从而导致递归。
  • @Terry 我明白了。在一个更大的过程中,我至少有 12 个字段,所以我希望避免为每个字段编写 getter 和 setter 的冗长。

标签: javascript vuejs2 watch


【解决方案1】:

您可以做的是创建一个安全阀来防止递归。比如:

export default {
  data() {
    return {
      isChangingMm: false,
      isChangingInches: false,
      // others
    }
  },
  watch: {
    inches: function (newVal) {
      if (!this.isChangingMm) {
        this.isChangingInches = true
        this.mm = newVal * 25.4
        this.isChangingInches = false
      }
    },
    mm: function (newVal) {
      if (!this.isChangingInches) {
        this.isChangingMm = true
        this.inches = newVal / 25.4
        this.isChangingMm = false
      }
    }
  },
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 2022-12-12
    • 1970-01-01
    • 2015-04-29
    相关资源
    最近更新 更多