[Vuejs]-Doubly linking 2 inputs in vuejs with a computation in the middle

0👍

✅

For this you can bind your <input> elements to computed properties, each with a setter.

When you update one input, you can set the values of both accordingly.

For example…

const mul = 1.5

new Vue({
  el: '#app',
  data: {
    val1: null,
    val2: null
  },
  computed: {
    input1: {
      get () {
        return this.val1
      },
      set (val) {
        this.val1 = val
        this.val2 = (val * mul).toFixed(2) // multiply to set val2
      }
    },
    input2: {
      get () {
        return this.val2
      },
      set (val) {
        this.val2 = val
        this.val1 = (val / mul).toFixed(2) // divide to set val1
      }
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.min.js"></script>
<div id="app">
<p>
<label for="input1">Input #1:</label>
<input id="input1" v-model="input1" type="number">
</p>
<p>
<label for="input2">Input #2:</label>
<input id="input2" v-model="input2" type="number">
</p>
</div>

Leave a comment