vue2.0函數(箭頭函數)的this作用域
阿新 • • 發佈:2017-09-26
ons popu content func efi defined 請求 ack logs
若想拿到後臺回傳的數據更新data裏的數據,不能在回調函數中直接使用this,而要用在外部函數定義的變量存儲的this,也就是當前vue的實例。
箭頭函數代碼改版(正確):
在做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從以上結果來看,在created下的函數this指向的是當前創建的vue實例,而在這些函數內部使用例如axios與後臺交互後回調函數的內部的this並非指向當前的vue實例;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 : 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實例(為什麽呢)了.
vue2.0函數(箭頭函數)的this作用域