我们在Laravel&Vue实战:任务管理系统二中使用vue-resouce或axios来发送接收http请求,我们提倡的格式一般是这样的:
axios.get('url').then( (response)=>{
this.data = response.data;
}).catch( (error)=>{
...
});
//vue-resource
this.$http.get('url').then((response)=>{
this.data = response.body;
},(response)=>{
...
});
注意这里的then((response)=>{})
,括号里面我们都用的是(response)=>{}
这种箭头函数的形式,但是呢最近发现有些同学会喜欢这么来写:
axios.get('url').then( function(response){
this.data = response.data;
}).catch(function(error){
console.log(error)
});
可以看到这个时候then()
里面是一个匿名函数:function(response){}
,表面上这只是格式上的差别,但是第二种匿名函数的形式,运行的时候就会出错,就会调用不到vue的data object 。
解决方法:
1. 用我们课程里提倡的箭头函数的形式啦,不要搞事情嘛~
2. 在http请求外层将vue实例所代表的this赋值给一个变量
vm = this;
axios.get('url').then( function(response){
vm.data = response.data;
}).catch();
3. 在创建vue实例的时候,将vue实例赋值给一个变量
var vm = new Vue({
...
axios.get('url').then(function(response){
vm.data = response.data;
}).catch();
如果你是在root vue实例里操作,以上三种方法都能行,但如果在vue component 中第三种方法就得创建一个空的vue实例来传递上面的vue实例,较为麻烦。
所以为了不给自己找事情,还是用我们课程里提倡的这种箭头函数的形式。
那this在上面两种环境下指的到底是什么呢? 下面进入读文档的时间 
如文档所描述:在非严格模式下 函数内部的this指的全局对象,在浏览器上全局对象就是window对象, 所以如果我们在上面的匿名函数中使用 console.log(this)
将this 输出 会看到 输出的是window对象。
而在箭头函数中this指的是包含它的执行环境的对象的this, 即我们在vue实例中使用箭头函数,那么箭头函数中的this指的就是 vue实例 中的this,即vue实例本身 同样的我们在上面的箭头函数中使用 console.log(this)
将会看到 输出的是vue实例。