成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術文章
文章詳情頁

淺談vue使用axios的回調函數(shù)中this不指向vue實例,為undefined

瀏覽:6日期:2022-11-20 13:01:41

今天在vue-cli腳手架搭建的項目中使用axios時,遇到無法解析this.$route的報錯信息,最后發(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ù)有個明顯的區(qū)別:箭頭函數(shù)內部的this是詞法作用域,在編寫函數(shù)時就已經(jīng)確定了,由上下文確定。而匿名函數(shù)的this指向運行時實際調用該方法的對象,無法在編寫函數(shù)時確定。

不可以當做構造函數(shù),也就是說,不可以使用 new 命令,否則會拋出錯誤。

this、arguments、caller等對象在函數(shù)體內都不存在。

不可以使用 yield 命令,因此箭頭函數(shù)不能用作 Generator 函數(shù)。

箭頭函數(shù)除了傳入的參數(shù)之外,其它的對象都沒有!在箭頭函數(shù)引用了this、arguments或者參數(shù)之外的變量,那它們一定不是箭頭函數(shù)本身包含的,而是從父級作用域繼承的。

補充知識:axios 中請求的回調函數(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)})

這兩組代碼的差別在于:請求成功后的回調函數(shù),一個使用匿名函數(shù),一個使用箭頭函數(shù)

匿名函數(shù)的指針指向->函數(shù)操作的本身

箭頭函數(shù)的指針指向->組件

也就是說當你需要使用到組件中聲明的變量或者函數(shù),就需要使用箭頭函數(shù)

以上這篇淺談vue使用axios的回調函數(shù)中this不指向vue實例,為undefined就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。

標簽: IOS
相關文章: