axios中this为undefined解决

    mounted()
    {
        function getUserAccount()
        {
            return axios.get("./data/demo_account.json");
        }

        function getUserPermissions() {
            return axios.get('./data/demo_permission.json');
        }
        axios.all([getUserAccount(), getUserPermissions()])
            .then(axios.spread(function (acct, perms) {
                // 两个请求现在都执行完成
                console.log(this.acct)
                console.log(this.perms)
                this.acct = acct.data
                this.perms = perms.data

            }));
    }
发现无法访问到根实例中声明的this.acct和this.perms,打印结果是undefined,原因式作用域的问题。

解决的方法是使用箭头函数=>

箭头函数和匿名函数有个明显的区别:箭头函数内部的this是词法作用域,在编写函数时就已经确定了,由上下文确定。而匿名函数的this指向运行时实际调用该方法的对象,无法在编写函数时确定。

    mounted()
    {
        function getUserAccount()
        {
            return axios.get("./data/demo_account.json");
        }

        function getUserPermissions() {
            return axios.get('./data/demo_permission.json');
        }
        axios.all([getUserAccount(), getUserPermissions()])
            .then(axios.spread((acct, perms)=> {
                // 两个请求现在都执行完成
                console.log(this.acct)
                console.log(this.perms)
                this.acct = acct.data
                this.perms = perms.data

            }));
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章