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