服务器之家:专注于服务器技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - 浅谈vue使用axios的回调函数中this不指向vue实例,为undefined

浅谈vue使用axios的回调函数中this不指向vue实例,为undefined

2021-10-06 15:34正版小火炉 JavaScript

这篇文章主要介绍了浅谈vue使用axios的回调函数中this不指向vue实例,为undefined,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

今天在vue-cli脚手架搭建的项目中使用axios时,遇到无法解析this.$route的报错信息,最后发现是作用域的问题。

1.解决方法:使用 =>

原代码:

?
1
2
3
4
5
6
7
8
9
10
11
axios.get('/user', {
  params: {
   ID: 12345
  }
 })
 .then(function (response) {
  console.log(response);
 })
 .catch(function (error) {
  console.log(error);
 });

修改为:

?
1
2
3
4
5
6
7
8
9
10
11
axios.get('/user', {
  params: {
   ID: 12345
  }
 })
 .then((response) => {
  console.log(response);
 })
 .catch((error) => {
  console.log(error);
 });

2.=>解析

在JS中,箭头函数并不是简单的function(){}匿名函数的简写语法糖,实际上,箭头函数和匿名函数有个明显的区别:箭头函数内部的this是词法作用域,在编写函数时就已经确定了,由上下文确定。而匿名函数的this指向运行时实际调用该方法的对象,无法在编写函数时确定。

不可以当做构造函数,也就是说,不可以使用 new 命令,否则会抛出错误。

this、arguments、caller等对象在函数体内都不存在。

不可以使用 yield 命令,因此箭头函数不能用作 Generator 函数。

箭头函数除了传入的参数之外,其它的对象都没有!在箭头函数引用了this、arguments或者参数之外的变量,那它们一定不是箭头函数本身包含的,而是从父级作用域继承的。

补充知识:axios 中请求的回调函数中的this指针问题

请看下面两组代码

?
1
2
3
4
5
6
7
8
9
10
11
this.axios.post(url, data)
.then(function(result) {
var resData = result.data
console.log(resData)
if (resData.status === 1) {
} else {
}
})
.catch(function (error) {
console.log(error)
})

?
1
2
3
4
5
6
7
8
9
10
11
this.axios.post(url, data)
.then((result) => {
var resData = result.data
console.log(resData)
if (resData.status === 1) {
} else {
}
})
.catch(function (error) {
console.log(error)
})

这两组代码的差别在于:请求成功后的回调函数,一个使用匿名函数,一个使用箭头函数

匿名函数的指针指向->函数操作的本身

箭头函数的指针指向->组件

也就是说当你需要使用到组件中声明的变量或者函数,就需要使用箭头函数

以上这篇浅谈vue使用axios的回调函数中this不指向vue实例,为undefined就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/bcfdsagbfcisbg/article/details/81910589

延伸 · 阅读

精彩推荐