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

網(wǎng)公網(wǎng)安備