vuejs - синхронизирует переменные в одном файле - PullRequest
0 голосов
/ 13 июня 2018

У меня есть файл 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>

Ответы [ 2 ]

0 голосов
/ 13 июня 2018

Ваш наблюдатель на input2 неверен, что вызывает бесконечный цикл (если вычисление основано на float, вам лучше использовать Math.round), оно должно быть:

input2: function (newVal) {
   this.input1 = newVal / this.conversionRate // not newVal*this.conversionRate
}

Но @Вамси Кришна должен быть лучшим решением.

Демонстрация:

app = new Vue({
  el: "#app",
  data: function () {
    return {
      input1: null,
      input2: null,
      conversionRate: 1
    }
  },
  watch: {
    input1: function (newVal) {
      this.input2 = newVal * this.conversionRate
    },
    input2: function (newVal) {
      this.input1 = newVal / this.conversionRate
    },
    conversionRate: function (newVal) {
      this.input2 = this.input1 * newVal
    }
  }
})
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<div id="app">
  <input v-model="input1">
  <input v-model="input2">
  <input v-model="conversionRate">
</div>
0 голосов
/ 13 июня 2018

Поскольку все три модели зависят друг от друга, это вызывает бесконечный цикл.

По вашему требованию вы можете использовать компьютерный установщик .

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>

SCRIPT

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

Вот рабочая скрипка

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...