.then(function(response) {
// handle success
console.log(response.data.data);
this.posts = response.data.data;
})
上面这段代码报错:Cannot set property ‘posts’ of undefined at eval…
这是很常见的错误,关键在this的作用域,如果我们改成
// 改成这样-------
.then(response=> {
console.log(response.data.data);
this.posts = response.data.data;
// 或者这样-------
let that = this
.then(function(response) {
// handle success
console.log(response.data.data);
that.posts = response.data.data;
})
把匿名函数改成箭头函数就可以,或先在匿名函数之外,声明变量that=this
虽然箭头函数是匿名函数的另一种写法,但是函数中this的指并不不同。
一般来说,匿名函数中this的上下文一般是window或者undefined(取决于是否处于严格模式之下);箭头函数没有单独的this值,它的this与声明时所在的上下文相同。
在这个例子中,可以用console.log(this)查看this的值
匿名函数的this打印出来是undefined
箭头函数的this打印出来是VueComponent
当然我们还可以显示地指定任何对象作为函数的上下文,这就是另一个要学习的话题了:apply和call