1

I've made multiple Vue watch fucntions affected each other. But It doesn't seem to operate as I intended.

When a user tab 'vinput01' and change, vinput02 change under only vinput01 functions. And When a user tab 'vinput02' and change value, 'vinput02' change only under vinput02 functions.

But now, my Code trigger infinite loop. Changing 'vinput01' affects 'vinput02' and 'vinput02' affects 'vinput01' at the same time.

Here is my Code. How can I avoid this problem??

data () {
  return {
   vinput01: '',
   vinput02: '',
  }
},
watch: {
 vinput01: function(_val) {
 this.vinput02 = _val *1.1
},
 vinput02: function(_val) {
 this.vinput01 = _val / 1.1
}

1 Answer 1

4

You need to have one property which is the 'source of truth'. Your problem really is that you have two values competing for this. To do this you can set one of your properties to be the primary value and the other as a computed property with a getter and setter. A good article about this can be found here, and in the excellent vuejs docs here.

Example code:

data(){
  return {
    vinput01:0,
  }
},
computed: {
  vinput02: {
    get: function(){
      return this.vinput01 * 1.1;
    },
    set: function(_val){
      this.vinput01 = _val / 1.1;
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.