前言
眾所周知axios是vue-resource后出現(xiàn)的Vue請(qǐng)求數(shù)據(jù)的插件。vue更新到2.0之后,作者尤大就宣告不再對(duì)vue-resource更新,而是推薦的axios。更多的詳細(xì)介紹大家可以參考這里://www.gxlcms.com/article/109444.htm
本文主要介紹了關(guān)于vue使用axios時(shí)this的指向問題,下面話不多說了,來一起看看詳細(xì)的介紹吧。
1.解決辦法
在vue中使用axios做網(wǎng)絡(luò)請(qǐng)求的時(shí)候,會(huì)遇到this不指向vue,而為undefined,可以使用箭頭函數(shù)"=>"來解決。如下:
methods: { loginAction(formName) { this.$axios.post('http://127.0.0.1/u/subLogin', { username: this.username, password: this.password }) .then(function(response){ console.log(this); //這里 this = undefined }) .catch((error)=> { console.log(error); //箭頭函數(shù)"=>"使this指向vue }); }); } }
2. 原因
ES6中的 箭頭函數(shù) "=>" 內(nèi)部的this是詞法作用域,由上下文確定(也就是由外層調(diào)用者vue來確定)。
3. 題外話
使用"=>"函數(shù),就可以告別之前的兩種寫法了:
bind(this)
來改變匿名函數(shù)的this指向
hack寫法 var _this= this;
:
loginAction(formName) { var _this= this; this.$axios.post("...") .then(function(response){ console.log(_this); //這里 _this 指向vue }) }); }
總結(jié)
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com