axios中的this - Go语言中文社区

axios中的this


今天别人使用axios中遇到了这个问题,因为感觉比较好奇,所以就帮着解决了一下,这篇博客用于记录一下此次错误的分析

这个是Vue中的钩子函数,在里面利用axios进行了一次get请求

        created() {
            axios.get('https://httpbin.org/get')
            .then(function(response) {
                console.log(this);
            })
            .catch(error => {
                alert('网络错误,不可访问');
                console.log(this);
            });
        },

这种情况下,输出this得到的’undefined’,但是当写成箭头函数的时候

axios.get('https://httpbin.org/get')
  .then(response => {
  console.log(this);
})
  .catch(error => {
  alert('网络错误,不可访问');
});

这样输出就是一个Vue的实例对象:

这里写图片描述

也许你想问,知道这个有什么用呢?举个例子,加入在methods对象中,有个方法需要在then方法中调用methods中的某个方法呢?如果按照ES5的写法,肯定是会报错的,所以针对ES5的写法,我有如下建议

methods: {
  doThis() {
    var that = this;
     axios.get('https://httpbin.org/get')
      .then(function() {
        that.dothat();
      })   
  },
  doThat() {
    //...
  }
}

这样就把this保存到当前作用域中了

另一种就是使用箭头函数,主要是箭头函数this指的就是词法作用域

methods: {
  doThis() {
    var that = this;
     axios.get('https://httpbin.org/get')
      .then(response => {
        this.doThat();
      })   
  },
  doThat() {
    //...
  }
}

学习是一个逐渐积累的过程,加油 ^_^

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/Dear_Mr/article/details/75734332
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-05-29 21:16:35
  • 阅读 ( 814 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢