axios中的this
来源:互联网 发布:java调用delphi的dll 编辑:程序博客网 时间:2024/06/04 18:47
今天别人使用axios中遇到了这个问题,因为感觉比较好奇,所以就帮着解决了一下,这篇博客用于记录一下此次错误的分析
这个是Vue中的钩子函数,在里面利用axios进行了一次get请求
created() { axios.get('https://httpbin.org/get') .then(function(response) { console.log(this); }) .catch(error => { alert('网络错误,不可访问'); console.log(this); }); },
这种情况下,输出this得到的’undefined’,但是当写成箭头函数的时候
axios.get('https://httpbin.org/get') .then(response => { console.log(this);}) .catch(error => { alert('网络错误,不可访问');});
这样输出就是一个Vue的实例对象:
也许你想问,知道这个有什么用呢?举个例子,加入在methods对象中,有个方法需要在then方法中调用methods中的某个方法呢?如果按照ES5的写法,肯定是会报错的,所以针对ES5的写法,我有如下建议
methods: { doThis() { var that = this; axios.get('https://httpbin.org/get') .then(function() { that.dothat(); }) }, doThat() { //... }}
这样就把this保存到当前作用域中了
另一种就是使用箭头函数,主要是箭头函数this指的就是词法作用域
methods: { doThis() { var that = this; axios.get('https://httpbin.org/get') .then(response => { this.doThat(); }) }, doThat() { //... }}
学习是一个逐渐积累的过程,加油 ^_^
阅读全文
0 0
- axios中的this
- Vue axios中this的指向问题
- vue使用axios中 this 指向问题
- Axios
- axios
- axios
- axios
- Axios
- axios
- axios
- axios
- axios
- axios
- axios
- axios
- axios中的http中的baseURL怎么用?
- Axios——axios在vue中的简单配置与使用
- axios在vue中的简单配置与使用
- vue2.0之axios使用详解(二)
- 输入捕获模式
- ELasticsearch集群搭建
- 双向队列deque
- 获取文件属性,目录信息和一些小笔记
- axios中的this
- 算法---面试题/--求N的阶乘N!中末尾0的个数
- 建造者模式(Builder Pattern)。
- 剑指offer 字符串的排列
- Linux之输入/输出重定向管理
- double im2double mat2gray之一二说
- 浅谈用户、组之管理指令
- MySQL安装
- 字符串问题