[Vuejs]-Logic Problem in Vue App is Causing an Infinite Loop due to Co-dependent Variables

0👍

Use the @input event listener. When you change the value in one input that changed will update the value of the other input.

<template>
  <div>
    <input v-model="value1" @input="update2"> 
    to 
    <input v-model="value2" @input="update1">
  </div>
</template>

<script>
const mul = 1.5;
export default {
  data: () => ({
    value1: null,
    value2: null
  }),
  methods: {
    update1() {
      this.value1 = this.value2 / mul;
    },
    update2() {
      this.value2 = this.value1 * mul;
    }
  }
};
</script>

You can make this work with watch, but then you’ll need to prevent the update loop with an additional check:

watch: {
  value1(val) {
    const tmp = val * mul;
    if (tmp !== this.value2) {
      this.value2 = tmp;
    }
  },
  value2(val) {
    const tmp = val / mul;
    if (tmp !== this.value1) {
      this.value1 = tmp;
    }
  }
},

But this code assumes that multiplying by x and then dividing by x results in the exact same number, and while that mathematically true, with floats (javascript’s number type) there are exceptions you’ll need to guard against (NaN, rounding) that will make the code complex.

I therefor recommend the input event-listener approach.

Leave a comment