【问题标题】:jQuery Ajax callback to a class method seemingly calling wrong instancejQuery Ajax 回调一个看似调用错误实例的类方法
【发布时间】:2018-02-18 09:44:21
【问题描述】:

我有一个带有 Vuex 商店的 Vue 实例。 Vue 组件可以调用 Vue 实例上的方法来确保某些对象存在于 Vuex 存储中。每个对象都存储为 ApiObject 类的一个实例。如果只知道对象的 ID,则将使用 jQuery Ajax 请求从服务器拉取对象。

出现以下问题:

我有两个 ApiObject,它们各自的对象 ID 为“0d3f7f10”和“f6a7d150”。第一个已经存在于 Vuex 存储中,但第二个仅通过它的 id 知道,因此触发了 Ajax 请求。

id为“f6a7d150”的对象启动ajax请求并命中正确的端点(/api/v1/f6a7d150),然后命中回调函数,这是ApiObject类的一个方法。

但是当调用回调时,我突然在错误的 ApiObject 实例中。我希望我正在调用 ApiObject“f6a7d150”的回调方法,但我正在调用“0d3f7f10”的回调方法。

这就是API调用和回调方法:

refresh () {
    console.log('Calling ' + this.id);
    jQuery.ajax({
        context: this,
        url: this.url(),
        method: 'GET',
        success: this.handleApiResult
    })
}

handleApiResult (result) {
    console.log('Handling ' + this.id);
    this.data = result['data'];
}

预期的控制台输出将是:

Calling f6a7d150
Handling f6a7d150

但实际上是这样的:

Calling f6a7d150
Handling 0d3f7f10

handleApiResult 中的结果变量包含 ID 为“f6a7d150”的正确对象,因此在 API 调用之前我们都在正确的实例中。

当我转储 Vuex Store 时,有两个 ID 为“0d3f7f10”的对象,一个有数据,另一个(我们刚刚从 API 中提取的那个)没有数据,所以只有它的 ID 是已知的。

Vue 组件在我的 Vue 实例上使用这些方法在 Vuex 中创建对象。控制台日志报告说,创建了 ID 为“f6a7d150”和“0d3f7f10”的对象,所以我不知道我的商店中怎么没有 ID 为“f6a7d150”的对象。

ensureObject (type, id, data) {
    if (!type || (!id && !data)) {
        return;
    }

    if (!id) {
        id = data.id;
    }

    if (this.$store.state[type].filter(o => o.id === id).length < 1) {
        console.log("Creating " + id);
        this.$store.state[type].push(new CiliatusObject(type, id, data));
    }
},

ensureObjects (type, ids, data) {
    if (!ids && !data) {
        return;
    }

    if (!ids) {
        data.forEach(obj => this.ensureObject(type, null, obj));
    }
    else {
        let that = this;
        ids.forEach(function (id) {
            that.ensureObject(
                type,
                id,
                data ? data.filter(o => o && o.id === id)[0] : undefined
            )
        });
    }
}

任何建议将不胜感激。

【问题讨论】:

    标签: javascript jquery ajax vue.js vuex


    【解决方案1】:

    好吧,我在用头撞墙几个小时后找到了它。

    在一个 Vue 组件的计算属性中,有这样一行:

    let obj = this.$store.state.filter(s =&gt; s.id = this.id);

    注意=,你会期望===.....

    【讨论】:

      猜你喜欢
      • 2019-11-26
      • 1970-01-01
      • 2015-06-10
      • 1970-01-01
      • 2011-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      相关资源
      最近更新 更多