Rafael Oviedo
Rafael Oviedo

Reputation: 9

How to change the value of a varible when another changes too?

Let's say I have two input tags (type number) where each one of them has a specific value (one starts in 0 and the other in 1000), and when I change the value of the first, for example from 0 to 200, the other one should change dynamically to the contrary respective value, in this case, 800.

input1 = 0 --> if change to 200 input2 = 1000 --> this changes to 800

All this must be done in Vue js. Please if someone can help me I'll be very thankful.

Upvotes: 0

Views: 151

Answers (2)

Chanckjh
Chanckjh

Reputation: 2597

You can use watcher to see changes on both data and update accordingly.

new Vue({
  el: '#app',
  data: {
    base: 1000,
    min: 0,
    max: 1000,
  },
  watch: {
    min: function(val) {
      this.max = this.base - val;
    },
    max: function(val) {
      this.min = this.base - val;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input type="number" id="min" v-model="min">
  <input type="number" id="max" v-model="max">
</div>

Upvotes: 1

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23510

If i correctly understand what you need, you can use computed:

new Vue({
  el: '#app',
  data: {
    num: null
  },
  computed: {
    num2() {
      return this.num ? Number(this.num) + 800 : null;
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input type="number" v-model="num">
  <input type="number" v-model="num2" disabled>
</div>

Upvotes: 1

Related Questions