程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

Vue 解惑之 关于axios 回调函数中 this 的指向

发布于2021-05-30 08:01     阅读(1366)     评论(0)     点赞(18)     收藏(0)


可以先运行下 完整代码 看看结果。

一、主要内容

  • SendGet 函数中的两个this打印情况
  • 如果 this 不相等,找找原因?

二、打印结果

打印结果

  • 两个this 是不一样的,out this 指向的是Vue 实例;
  • inner this 指向的是window;

三、结果分析

  • 其实两个this指向不一样是因为调用它们所在函数的对象不一样,out this所在的函数SendGet 是被Vue 实施调用,
  • inner this 所在的回调函数时是在执行栈中被执行,this指向就是window了

四、修改 this 的指向方法

 这个修改哪个this?修改的是inner this,保持跟out this 指向一致,这样我们请求返回的数据就赋&给Vue实例 中的 data 对象,这样页面呈现的就是最新数据。

  • 方法一,将回调函数形式改为箭头函数,(详解参考 箭头函数中this的指向

       SendGet:function(){
            console.log("out this:",this)
            axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5')
            .then(res=>{
              console.log("inner this:",this)
              // console.log(res.data);
            });
          },
    
  • 方法二,变量传值

     SendGet:function(){
            console.log("out this:",this)
            var _this = this;
            axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5')
            .then(function(res){
              console.log("inner this:",_this)
              // console.log(res.data);
            });
          },
    

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>认识Vue</title>
 <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>

 <div id="app">
   {{message}}
   <button @click='OnClick'>点击</button>
   <button @click='SendGet'>Get请求</button>

 </div>
 
 <script>
   new Vue({
     el:'#app',
     data:{
       message: 'Hello, Vue!',
     },
     methods:{
       OnClick:function(){
         console.log('this:',this);
         console.log('click');
       },
       SendGet:function(){
         console.log("out this:",this)
         axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5')
         .then(function(res){
           console.log("inner this:",this)
           // console.log(res.data);
         });
       },
     }
   });
 </script>
</body>
</html>



所属网站分类: 技术文章 > 博客

作者:强哥你们辛苦了

链接:http://www.qianduanheidong.com/blog/article/115830/b45a58e37d8228c47411/

来源:前端黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

18 0
收藏该文
已收藏

评论内容:(最多支持255个字符)