Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 create_casenr of my instance is triggered.

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

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 dataand this.name (OK)
  • but name 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 id), except for name.

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

like image 902
WoJ Avatar asked Oct 24 '16 12:10

WoJ


1 Answers

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:

$.ajax({
    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: https://stackoverflow.com/a/40200989/654825

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

like image 81
Mani Avatar answered Sep 19 '22 05:09

Mani