vue使用axios中 this 指向问题
2018-01-12 22:18
671 查看
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(error); //箭头函数"=>"使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 }) }); }
相关文章推荐
- vue使用axios中 this 指向问题
- vue使用axios时关于this的指向问题详解
- vue中使用定时器时this指向问题
- 处理vue中使用Axios调用接口时出现的ie数据处理问题
- react组件中使用ajax时this的指向问题
- 关于vue2.x使用axios以及http-proxy-middleware代理处理跨域的问题
- vue使用axios跨域请求数据问题详解
- JavaScript call apply使用 JavaScript对象的方法绑定到DOM事件后this指向问题
- 关于在vue中结合数组方法的this的指向问题
- vue使用axios调用豆瓣API跨域问题
- IE6,7,8使用attachEvent时this指向问题
- 使用vue-cli脚手架 与 axios 请求数据 配置代理进行跨域访问数据问题
- 在vue中使用axios跨域访问数据,用proxyTable解决跨域问题
- vue 使用axios 跨域请求数据的问题
- 解决vue中使用Axios调用接口时出现的ie数据处理问题
- 在 Vue 结合 Axios 使用过程 中 post 方法,后台无法接受到数据问题
- vue-cli的axios使用方法,get、post请求的跨域问题解决
- 解决使用attachEvent函数时,this指向被绑定的元素的问题的方法
- 使用vue-axios请求geoJson数据报错的问题