vue2.0函數(箭頭函數)的this作用域


在做vue項目時用到了axios,但是發現axios請求之后的回調函數里this並不指向當前vue實例,從而導致瀏覽器報錯。

出錯代碼及結果:

  created : function(){
      axios.get('static/data.json').then(function(res){
          console.log(this)    //undefined this.user = res.data.user
   })
  }

(報錯截圖)

普通函數代碼改版(正確):
 created : function(){
      var _this = this
      axios.get('static/data.json').then(function(res){
          console.log(this)    //undefined
          console.log(_this)   //VueComponent {_uid: 1, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
      _this.user = res.data.user
   })
  }
從以上結果來看,在created下的函數this指向的是當前創建的vue實例,而在這些函數內部使用例如axios與后台交互后回調函數的內部的this並非指向當前的vue實例;
若想拿到后台回傳的數據更新data里的數據,不能在回調函數中直接使用this,而要用在外部函數定義的變量存儲的this,也就是當前vue的實例。
箭頭函數代碼改版(正確):
created : function(){
      axios.get('static/data.json').then((res) => {
          console.log(this)      //VueComponent {_uid: 1, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …} this.user = res.data.user
   })
  }

 箭頭函數相當於匿名函數,並且簡化了函數定義。看上去是匿名函數的一種簡寫,但實際上,箭頭函數和匿名函數有個明顯的區別:箭頭函數內部的this是詞法作用域,由上下文確定。此時this在箭頭函數中已經按照詞法作用域綁定了。很明顯,使用箭頭函數之后,箭頭函數指向的函數內部的this已經綁定了外部的vue實例了.


免責聲明!

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



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