【问题标题】:Cannot access Vue data set within mounted via ajax无法通过 ajax 访问挂载的 Vue 数据集
【发布时间】:2019-03-05 07:07:23
【问题描述】:

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

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

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;
    });
}

});

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

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

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

    或者你可以使用.bind关闭函数范围this

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

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

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

    或者你可以在$.getJSON之前给this加上别名

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

    【讨论】:

    • 绑定和粗箭头解决方案对我有用。感谢您的帮助!
    【解决方案2】:

    我的猜测是 this 在回调函数中没有绑定到你的 vue 实例。试试下面的

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

    【讨论】:

    • 这个解决方案也很有效,我想我已经尝试过了。我注意到的是,当访问我的 updateTableData() 方法中的数据时,我无法访问“this.allJson”,因为我得到了空的 observable,但是如果我访问“this.allJson.users”,那么我会得到所有用户期待。感谢您发布此解决方案。
    • 没问题。很高兴事情最终为你解决了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多