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

后端 未结 3 1533
悲哀的现实
悲哀的现实 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:03

    not same scope for this.name

    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);
    }.bind(this))
    

    add a bind(this)

    0 讨论(0)
  • 2021-01-01 22:08

    Another thing that plays a role here is how Vue.js updates the DOM. For details read this section in the documentation: Async Update Queue

    In short use "nexTick" callback to process your code after Vue.js is done updating the DOM.

    methods: {
       someMethod() {
          var self = this;
          $.ajax({
            url: 'http://...',
          }).done(function (data) {
            self.a = data.a;
            self.b = data.b;
            self.$nextTick(function () {
               // a and b are now updated
            }
          });
       }
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题