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. 题外话

使用"=>"函数,就可以告别之前的两种写法了:

  1. bind(this)来改变匿名函数的this指向
  2. 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

最新文章

  1. poj[2104]K-th Number
  2. 网页播放器(jsp、js)
  3. python基础-range用法_python2.x和3.x的区别
  4. linux下命令运行目录上程序前面要加./
  5. SSM的各个配置文件
  6. HTML5秘籍读书笔记
  7. GSS1 spoj 1043 Can you answer these queries I 最大子段和
  8. Android学习笔记12:图像渲染(Shader)
  9. 【转】Eclipse中创建并运行Servlet项目
  10. Spring MVC 遇到的一点点问题(转)
  11. CXF之"@XmlType.name 和 @XmlType.namespace 为类分配不同的名称"错误
  12. Select标签 根据value值默认选中 Jquery
  13. how tomcat works读书笔记 七 日志记录器
  14. 深入理解.net - 3.类型Type
  15. Java中获取系统时间的四种方式
  16. 【转】VMware 14 Pro安装mac os 10.12
  17. 基于InfluxDB实现分页查询功能
  18. Lambda表达式select()和where()的区别
  19. ROC,AUC,Precision,Recall,F1的介绍与计算(转)
  20. Android蓝牙联机Demo解析

热门文章

  1. C#post调用接口并上传文件
  2. Django(1.7 part1)
  3. 使用python绘制词云
  4. .startsWith和endsWith的使用方法与说明
  5. 关于Scrapy爬虫项目运行和调试的小技巧(下篇)
  6. matplotlib bar函数重新封装
  7. 关于Jwt的一些思考
  8. 使用JMX透过防火墙远程监控tomcat服务
  9. wget 升级
  10. hadoop-06-http服务