user5296896
user5296896

Reputation: 179

Vue.js: Binding two input to each other

I'm currently starting on using vue.js, and have encountered a situation.

I wish to bind two inputs for example C = A - B. and B = A - C, where A is constant and a change in B or C will affect the other.

I successfully bind C using v-model and placing it in computed. However, when I tried the same for B, it ran into an infinite loop.

This should be something very simple however, I can't seem to find a solution to it. Any help is appreciated thank you!

Edit: Code is included below. I wish for use the be able to key into either down_payment or loan_amount. After which it will calculate the other value automatically. However this way seems to make it go into a infinite loop

<input type="number" v-model="down_payment" class="form-control-right" placeholder="Downpayment" value="{{ down_payment }}" number>
<input type="number" v-model="loan_amount" placeholder="Loan Amount" value="{{loan_amount }}" number>

My javascript

 new Vue({
    el: '#calculator',
    data: {
        asking_price: 60000,
    },
    computed: {
        loan_amount: function(){
            return this.asking_price - this.downpayment;
        },
        down_payment : function(){
            return this.asking_price - this.loan_amount;
        },
    }
 });

Upvotes: 5

Views: 4479

Answers (2)

Roy J
Roy J

Reputation: 43881

You really have two independent variables and one that is computed but needs to be writable and handle the dependencies in its setter.

   data: {
     asking_price: 60000,
     down_payment: 20
   },
   computed: {
     loan_amount: {
       get: function() {
         return this.asking_price - this.down_payment;
       },
       set: function(newValue) {
         this.down_payment = this.asking_price - newValue;
       }
     }
   }

Fiddle

Upvotes: 6

PatrickSteele
PatrickSteele

Reputation: 14677

I'm still learning vue myself, but I'm wondering if it would be better to just define b and c as data properties and then use a watch to recompute one or the other when there's a change (instead of using computeds). Something like this:

        var vm = new Vue({
          el: '#calculator',
          data: {
            a: 10,
            b: 0,
            c: 10
          },
          watch: {
            'b' : function(newVal, oldVal) {
                this.c = this.a - newVal;
            },
            'c' : function(newVal, oldVal) {
                this.b = this.a - newVal;
            }
          }
        });

Upvotes: 0

Related Questions