vue在axios中 this 指向問題


1.解決辦法

在vue中使用axios做網絡請求的時候,會遇到this不指向vue,而為undefined,可以使用箭頭函數"=>"來解決。如下:

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(this); //箭頭函數"=>"使this指向vue }); }); } }

2. 原因

ES6中的 箭頭函數 "=>" 內部的this是詞法作用域,由上下文確定(也就是由外層調用者vue來確定)。

3. 題外話

使用"=>"函數,就可以告別之前的兩種寫法了:

  1. bind(this)來改變匿名函數的this指向
  2. hack寫法 var _this= this;

    loginAction(formName) {
        var _this= this; this.$axios.post("...") .then(function(response){ console.log(_this); //這里 _this 指向vue }) }); }

 

 

來源:

https://segmentfault.com/a/1190000012533993


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM