vue踩坑:axios使用this指针

前言

在vue中,请求后端接口的模块有三种:
  • vue-resource
  • axios
  • fetch
这我们使用axios去请求后端接口。

安装

进入vue项目的目录,执行:

npm install axios --save

使用

axios支持的http请求方法如下

  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.options(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])

本篇不重点介绍axios的使用,这里我们以get为例,在使用axios接收接口返回的时候,需要使用箭头=>符号获取正确的this指针。

 this.$axios
      .get("/userInfo")
      .then(
        (response) =>
          // handle success
          (this.userdata = response.data)
      )
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });

如果不想用箭头函数可以在外部先用变量获取this指针,但是建议还是使用上面的写法。

 let that = this;
this.$axios .get("/userInfo") .then( function(response){
// handle success       (that.userdata = response.data) ) .catch(function (error) { // handle error console.log(error); }) .then(function () { // always executed });

 

博主:测试生财(一个不为996而996的测开码农)

座右铭:专注测试开发与自动化运维,努力读书思考写作,为内卷的人生奠定财务自由。

内容范畴:技术提升,职场杂谈,事业发展,阅读写作,投资理财,健康人生。

csdn:https://blog.csdn.net/ccgshigao

博客园:https://www.cnblogs.com/qa-freeroad/

51cto:https://blog.51cto.com/14900374

微信公众号:测试生财(定期分享独家内容和资源)

 

posted @ 2020-11-05 07:57  公众号-测试生财  阅读(2078)  评论(0编辑  收藏  举报