Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js: Binding two input to each other

Tags:

vue.js

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;
        },
    }
 });
like image 775
user5296896 Avatar asked Aug 23 '16 06:08

user5296896


People also ask

Does Vue have 2 way data binding?

Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries. The v-model directive makes two-way binding between a form input and app state very easy to implement.

What is the Vuejs directive for 2 way binding on input tags?

In Vue, two-way binding is accomplished using the v-model directive.

Does Vue have data binding?

Vue provides its own set of directives used to dynamically bind our data to the templates. Text Binding: It is used when we need to bind the content of any HTML in Vue. The syntax for using text binding is by using the v-text directive in any HTML element and a data property should be assigned to it.


1 Answers

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

like image 73
Roy J Avatar answered Nov 04 '22 11:11

Roy J