无法访问通过 ajax 挂载的 Vue 数据集 [英] Cannot access Vue data set within mounted via ajax

查看:22
本文介绍了无法访问通过 ajax 挂载的 Vue 数据集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Vue2.我在我的挂载方法中通过 ajax 获取 json 数据.然后我将该数据设置为一个数据变量,希望能够从 mount 之外的其他方法访问它,但我得到的只是一个空的 observable.

I am using Vue2. I am getting json data via ajax in my mounted method. I then set that data to a data variable expecting to be able to access it from other methods outside of mounted, but all I get is an empty observable.

有什么建议/建议吗?感谢您的帮助.

Any suggestions/advice? Thanks for the help.

var vm = new Vue({
el: '#app',
data: function () {
    return {
        allJson: []
    };
},
methods: {
    updateTableData:  function(isActive) {
        // cannot access this.allJson here
    }
},
mounted: function() {
    $.getJSON(Routes.USERS_GET_JSON, function(json) {
        this.allJson = json;
    });
}

});

推荐答案

我已经很久很久没有使用 jQuery,但是如果我没记错的话你需要显式声明 this 如果你想在回调中使用它,否则你会得到一些意想不到的东西.但是,我不知道 $.getJSON 是否支持它,即使它是一个包装器.因此,您可以尝试以下操作:

I haven't used jQuery in a long, long time, but if I remember correctly you need to explicitly declare the context of this if you wish to use it within the callback, else you get something unexpected. However, I don't know if $.getJSON supports it even though it's a wrapper. So you can try the following:

$.getJSON(Routes.USERS_GET_JSON, function(json) {
    this.allJson = json;
}, {
    context: this
})

或者你可以使用函数的 .bind 来限定 this

Or you can use .bind off of the function to scope this

$.getJSON(Routes.USERS_GET_JSON, function(json) {
    this.allJson = json
}.bind(this))

或者,如果您正在使用 babel(您可能是)进行转换,则可以使用 fat arrow 语法:

Or if you're tranpsiling down with babel (which you probably are) you can use fat arrow syntax:

$.getJSON(Routes.USERS_GET_JSON)
    .done( (json) => {
        this.allJson = json
    })

或者你可以在 $.getJSON

let _self = this

 $.getJSON(Routes.USERS_GET_JSON, function(json) {
    _self.allJson = json
 })

这篇关于无法访问通过 ajax 挂载的 Vue 数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆