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

后端 未结 3 1532
悲哀的现实
悲哀的现实 2021-01-01 21:48

I have a VueJS instance with some data :

var vm = new Vue({
    el: \'#root\',
    data: {
        id: \'\',
        name: {
            firstname: \"\", 
           


        
3条回答
  •  一整个雨季
    2021-01-01 22:21

    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

提交回复
热议问题