axios中的this

来源:互联网 发布:java调用delphi的dll 编辑:程序博客网 时间:2024/06/04 18:47

今天别人使用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() {    //...  }}

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

原创粉丝点击