Vue中axios请求使用时候,比如要用bind(this)
或者var _this = this
才能获取VueComponent对象
比如:
var _this = this;
axios("/brandInfo/deleteBrandInfo", _this.param({
brandId: _this.data[_this.deleteIndex].id,
})).then(function (res) {
if (res.data.code == 1) {
_this.pullBrandRoute();
} else {
throw res.data.message;
}
}).catch(function (err) {
_this.$Message.error(err);
});
我以为是promise的问题,于是自己写了一个promise
function p(type){
return new Promise((resolve,reject)=>{
if (type=='yes') {
setTimeout(()=>{
resolve('resolved');
},5000);
}else{
setTimeout(()=>{
reject('rejected');
},5000);
}
})
}
function resolve(){
console.log('before:',this)
p('yes').then(res=>{
console.log('res',this);
console.log(res);
}).catch(err=>{
console.log('err',this);
console.log(err);
})
}
打印出来的this都是指向了window
为什么同是promise 在then方法中的this指向不同呢?
JavaScript 里普通函数(通过
function
定义)中的this
是动态绑定的,也就是说它不看你如何定义,而是看如何使用。像你最后的例子中,相信你是直接
resolve()
调用,那么非严格模式下这个函数里面的this
就是window
。后面的两个this
因为是在箭头函数里,所以直接跳过箭头函数用了上一层resolve
里的this
,也同样是window
。如果你通过
resolve.call(p)
调用,那么可以观察到三个this
也会指向p
推荐阅读这篇文章《JavaScript this 的六道坎》了解
this
的几种变化。