今天在學習使用axios的時候,想要將響應內容存儲到當前Vue對象中,考慮到將response.data賦值給this.info就可以實現,但是在用的時候卻發現使用箭頭函數能夠正常實現,但是在使用普通函數的時候卻無法實現,兩組代碼如下:
箭頭函數(能夠正常實現賦值):
var url="armour?aname="+$("#input1").val(); $("#div2").html(url); new Vue({ el:'#div1', data:{ info:'' }, methods:{ getInfo:function () { axios .get(url).then(response=>(this.info=response.data))//箭頭函數 .catch(function (error) { console.log(error); }) } } })
此時在箭頭函數中的this是當前對象,所有使用this.info就能夠將響應內容賦值給當前Vue對象的info。
普通函數(無法正常賦值):
var url="armour?aname="+$("#input1").val(); $("#div2").html(url); new Vue({ el:'#div1', data:{ info:'' }, methods:{ getInfo:function () { axios .get(url).then(function (response) {//普通函數 this.info=response.data; }) .catch(function (error) { console.log(error); }) } } })
普通函數無法實現的原因:
普通函數中的this並不是代表當前的Vue對象(這個this代表哪個對象目前博主也還不清楚),因此使用this.info並不能給當前Vue對象的info賦值。
驗證和解決:
如果一定要使用普通函數給當前Vue對象的data賦值,可以在使用普通函數之前先將this賦值給一個變量,在普通函數內使用此變量對當前Vue對象的data進行賦值,代碼如下:
var url="armour?aname="+$("#input1").val(); $("#div2").html(url); new Vue({ el:'#div1', data:{ info:'' }, methods:{ getInfo:function () { var _this=this;//將代表當前Vue實例的this賦值給_this axios .get(url).then(function (response) { _this.info=response.data;//將響應內容賦值給_this.info }) .catch(function (error) { console.log(error); }) } } })
參考博文: