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

            }));
    }

 

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