首页 > 解决方案 > 当另一个字段发生变化时更新一个字段 - Vue

问题描述

我试图从本质上创建一个双向计算器,并且我选择使用英寸到毫米作为示例。

在此处查看沙箱: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>

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

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

标签: javascriptvuejs2watch

解决方案


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

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
      }
    }
  },
}

推荐阅读