Search code examples
ajaxvuejs2vue.jsvue-resource

Vue2: Why do I get infinite $http.get requests when I assign property from response?


I make $http.get call to back-end where I process data and return a result, and I want to assign property to this dynamically (the property is declared in data list):

watch: {
    send_amount: function() {
        this.updateAmount('my_param1');
    },
    receive_amount: function() {
        this.updateAmount('my_param2');
    },
},

methods: {
    updateAmount: function(_par) {

        var vVar = this;

        this.$http.get('http://www.website.dev/api/calculate', { params: { rec: _par } })
                .then(function(response) {

                    _results = JSON.parse(response.data);

                    $.each(_results, function(k, v) {

                        vVar[k] = v; // << this causes the $http.get request to be sent over and over, infinitely.

                    });

                });
    }

}

Solution

  • As you don't want to call updateAmount method when the variables are changed programatically, You can instead remove the watch and use v-on:change in the input fields of these variables, like following:

    <input v-model="receive_amount" v-on:change"updateAmount" />