WoJ WoJ - 1 year ago 154
jQuery Question

How to update data of a VueJS instance from a jQuery AJAX call?

I have a VueJS instance with some data :

var vm = new Vue({
el: '#root',
data: {
id: '',
name: {
firstname: "",
lastname: "",
country: "",
valueset: false
// ...

In my HTML, I also have :

<input class="id" type="text" size="4" maxlength="4" v-model.lazy="id" v-on:change="create_casenr">

Therefore after filling up this field, the method
of my instance is triggered.

create_casenr: function(event) {
// update the full name of user
url: 'http://elk.example.com:9200/users/user/' + this.id
.done(function(data) {
this.name = data._source;
this.name.valueset = true;
// ...

What happens is that :

  • create_casenr
    is called upon the change in the field (OK)

  • the AJAX call goes through successfully, I see the expected output on the console for both

  • but
    is not updated in the instance of VueJS.

I can see it is not updated because other parts of my code which rely on it do not see it; I also checked with the VueJS Chrome add-on and all the variables are correctly set (including
), except for

Is there a specific way I should address the data of a VueJS instance when modified via a jQuery AJAX call?

Answer Source

You have a scope issue of this.name in your AJAX success handler.

The this.name inside is not the same as this.name in your Vue component. So your name is not getting set in the Vue component.

You may use arrow functions to get around this issue:

    url: 'http://elk.example.com:9200/users/user/' + this.id
    }).done(data => {
        this.name = data._source;  // 'this' points to outside scope
        this.name.valueset = true;

Similar answer: http://stackoverflow.com/a/40200989/654825

More info on Arrow functions: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download