axios中的this指向问题
axios中this指向问题的介绍
·
axios特点
场景
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。在进行Vue实验时,需要用到axios进行接口请求,并将返回的内容传递到Vue的data选项中。正常情况下,会使用this.list = response.data的格式进行赋值,但this的指向恰恰是最容易被忽略的地方。
其特点如下:
1.从浏览器中哦=创建XMLHttpRequest
2.从node.js中发出http请求
3.支持Promise API
4.拦截请求和响应
5.转换请求和响应数据
6.取消请求
7.自动转换JSON数据
8.客户端支持防止CSRF/XSRF
解决axios 中this 指向问题
1.使用箭头函数来解决
示例:
methods:{
loginAction(formName){
this.$axios.post('http://124.0.0.1/u.subLogin',{
username:this.username,
password:this.password,
}).then((response)=>{
console.log(this.list);
//this.list =response.data
}).catch((err)=>{
console.log(this);
})
}
}
2.使用.bind(this)在回调函数后面解决
示例:
getRequest:function(){
axios.get('http:/124.0.0.1/u/subBOf',{
username:this.username,
password:this.password
}).then(function(resp){
console.log(this.list)
//this.list = resp.data
}).bind(this)
.catch(function(err){
console.log(err)
})
}
3.使用that传递this变量
示例:
getRequest:function(){
var that =this;
axios.get('http:/124.0.0.1/s/shus',{
username:this.username,
passoword:this.password
}).then(function(resq){
console.log(that.list)
//that.list = resq.data
}).catch(function(err){
console.log(err)
})
}
更多推荐
已为社区贡献1条内容
所有评论(0)