首页 > 解决方案 > vuejs - 在同一个文件中同步变量

问题描述

我有一个 vue(版本 2.x)文件,其中有 3 个字段 -input1 x input2 = result

现在,当我更改其中任何一个时,其他两个应该即时更新。我尝试使用watch属性,但这会导致无限循环,因为观察者不断互相调用。

我在这里缺少任何与 vue 相关的助手吗?任何帮助,将不胜感激。

请参阅此示例代码。

<template>
  <input v-model="input1"></input>
  <input v-model="input2"></input>
  <input v-model="conversionRate"></input>
</template>

<script>
export default {
  data() {
    input1: null,
    input2: null,
    conversionRate: null
  },
  watch: {
    input1() {
      this.input2 = this.input1 * this.conversionRate
    },
    input2() {
      this.input1 = this.input2 * this.conversionRate
    },
    conversionRate() {
      this.input2 = this.input1 * this.conversionRate
    }
  }
}
</script>

标签: javascriptvue.jsvuejs2

解决方案


由于所有三个模型都相互依赖,因此会导致无限循环。

根据您的要求,您可以使用计算的 setter

HTML

<div id="app">
  <input type="number" placeholder="amount" v-model="inputA"> X
  <input type="number" placeholder="rate" v-model="conversionRate"> =
  <input type="number" placeholder="total" v-model="total">
</div>

脚本

new Vue({
  el: "#app",
  data: {
    total: 0,
    conversionRate: 1
  },
  computed: {
    inputA: {
      get() {
        return this.total / this.conversionRate;
      },
      set(newVal) {
        this.total = newVal * this.conversionRate;
      }
    }
  }
});

这是工作小提琴


推荐阅读