vue使用axios中 this 指向问题
2024-08-31 13:09:38
1.解决办法
在vue中使用axios做网络请求的时候,会遇到this不指向vue,而为undefined,可以使用箭头函数"=>"来解决。如下:
methods: {
loginAction(formName) {
this.$axios.post('http://127.0.0.1/u/subLogin', {
username: this.username,
password: this.password
})
.then(function(response){
console.log(this); //这里 this = undefined
})
.catch((error)=> {
console.log(this); //箭头函数"=>"使this指向vue
});
});
}
}
2. 原因
ES6中的 箭头函数 "=>" 内部的this是词法作用域,由上下文确定(也就是由外层调用者vue来确定)。
3. 题外话
使用"=>"函数,就可以告别之前的两种写法了:
- bind(this)来改变匿名函数的this指向
hack写法
var _this= this;
:
loginAction(formName) {
var _this= this;
this.$axios.post("...")
.then(function(response){
console.log(_this); //这里 _this 指向vue
}) });
}
原文地址:https://segmentfault.com/a/1190000012533993
最新文章
- poj[2104]K-th Number
- 网页播放器(jsp、js)
- python基础-range用法_python2.x和3.x的区别
- linux下命令运行目录上程序前面要加./
- SSM的各个配置文件
- HTML5秘籍读书笔记
- GSS1 spoj 1043 Can you answer these queries I 最大子段和
- Android学习笔记12:图像渲染(Shader)
- 【转】Eclipse中创建并运行Servlet项目
- Spring MVC 遇到的一点点问题(转)
- CXF之";@XmlType.name 和 @XmlType.namespace 为类分配不同的名称";错误
- Select标签 根据value值默认选中 Jquery
- how tomcat works读书笔记 七 日志记录器
- 深入理解.net - 3.类型Type
- Java中获取系统时间的四种方式
- 【转】VMware 14 Pro安装mac os 10.12
- 基于InfluxDB实现分页查询功能
- Lambda表达式select()和where()的区别
- ROC,AUC,Precision,Recall,F1的介绍与计算(转)
- Android蓝牙联机Demo解析