axios的普通函數和箭頭函數下的this的區別


  今天在學習使用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);
                    })
                }
            }
        })

參考博文:

https://www.cnblogs.com/stella1024/p/7598541.html


免責聲明!

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



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