淺談vue使用axios的回調(diào)函數(shù)中this不指向vue實(shí)例,為undefined
今天在vue-cli腳手架搭建的項(xiàng)目中使用axios時,遇到無法解析this.$route的報(bào)錯信息,最后發(fā)現(xiàn)是作用域的問題。
1.解決方法:使用 =>
原代碼:
axios.get(’/user’, { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
修改為:
axios.get(’/user’, { params: { ID: 12345 } }) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); });
2.=>解析
在JS中,箭頭函數(shù)并不是簡單的function(){}匿名函數(shù)的簡寫語法糖,實(shí)際上,箭頭函數(shù)和匿名函數(shù)有個明顯的區(qū)別:箭頭函數(shù)內(nèi)部的this是詞法作用域,在編寫函數(shù)時就已經(jīng)確定了,由上下文確定。而匿名函數(shù)的this指向運(yùn)行時實(shí)際調(diào)用該方法的對象,無法在編寫函數(shù)時確定。
不可以當(dāng)做構(gòu)造函數(shù),也就是說,不可以使用 new 命令,否則會拋出錯誤。
this、arguments、caller等對象在函數(shù)體內(nèi)都不存在。
不可以使用 yield 命令,因此箭頭函數(shù)不能用作 Generator 函數(shù)。
箭頭函數(shù)除了傳入的參數(shù)之外,其它的對象都沒有!在箭頭函數(shù)引用了this、arguments或者參數(shù)之外的變量,那它們一定不是箭頭函數(shù)本身包含的,而是從父級作用域繼承的。
補(bǔ)充知識:axios 中請求的回調(diào)函數(shù)中的this指針問題
請看下面兩組代碼
①
this.axios.post(url, data).then(function(result) {var resData = result.dataconsole.log(resData)if (resData.status === 1) {} else {}}).catch(function (error) {console.log(error)})
②
this.axios.post(url, data).then((result) => {var resData = result.dataconsole.log(resData)if (resData.status === 1) {} else {}}).catch(function (error) {console.log(error)})
這兩組代碼的差別在于:請求成功后的回調(diào)函數(shù),一個使用匿名函數(shù),一個使用箭頭函數(shù)
匿名函數(shù)的指針指向->函數(shù)操作的本身
箭頭函數(shù)的指針指向->組件
也就是說當(dāng)你需要使用到組件中聲明的變量或者函數(shù),就需要使用箭頭函數(shù)
以上這篇淺談vue使用axios的回調(diào)函數(shù)中this不指向vue實(shí)例,為undefined就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
