如何从jQuery AJAX调用更新VueJS实例的数据?

WoJ*_*WoJ 12 ajax jquery vue.js

我有一个带有一些数据的VueJS实例:

var vm = new Vue({
    el: '#root',
    data: {
        id: '',
        name: {
            firstname: "", 
            lastname: "", 
            country: "", 
            valueset: false
        },
// ...
Run Code Online (Sandbox Code Playgroud)

在我的HTML中,我也有:

<input class="id" type="text" size="4" maxlength="4" v-model.lazy="id" v-on:change="create_casenr">
Run Code Online (Sandbox Code Playgroud)

因此,在填写此字段后,将create_casenr触发我的实例的方法.

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);
    })
// ...
Run Code Online (Sandbox Code Playgroud)

会发生什么:

  • create_casenr 被称为现场变化(好)
  • AJAX调用成功通过,我在控制台上看到了两者的预期输出data和this.name(OK)
  • 但是 name在VueJS的实例中没有更新.

我可以看到它没有更新,因为依赖它的代码的其他部分看不到它; 我还检查了VueJS Chrome插件并且所有变量都已正确设置(包括id),除了name.

当通过jQuery AJAX调用修改时,是否有一种特定的方法来解决VueJS实例的数据?

Man*_*ani 15

您this.name的AJAX成功处理程序中存在范围问题.

该this.name内部是不一样this.name在你的Vue公司的组成部分.因此,您的名称未在Vue组件中设置.

您可以使用箭头函数来解决此问题:

$.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;
    });
Run Code Online (Sandbox Code Playgroud)

类似的答案:https://stackoverflow.com/a/40200989/654825

有关Arrow函数的更多信息:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

  • 对于未来的读者:截至2016年10月,IE不支持箭头功能(可能永远不会是因为IE 11是最后一个IE).Edge,Chrome,Firefox确实有效. (4认同)

hig*_*rfs 8

不同的范围 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))
Run Code Online (Sandbox Code Playgroud)

添加一个 bind(this)