我最近开始使用Vue 2并使用Pexels API处理一个小项目 . 我正在尝试调用API以获取一些图像URL以加载到数据对象中的属性 . 但是,我无法将数据属性传递给回调 . 我认为我的代码可以更好地解释事情 . 这是整个Vue实例:
export default {
name: 'Gallery',
data() {
return {
pics: [1,2],
count: 100
}
},
mounted() {
console.log(this.count) //I can see this value
console.log(this.pics) //I can also see this value
let test = this.count;
pexelsClient.getPopularPhotos(10, 1)
.then(function(result){
console.log(test); //This will allow me to see the value
console.log(this.count) // This gets me an error message see below.
console.log(result.photos[0].url);
return result;
})
}//End of mounted function
}//End of Vue instance
我 console.log(this.count)
时出现错误信息:
未捕获(承诺)TypeError:无法读取未定义的属性'count'
我曾尝试阅读有关此事的大量文章,并查看了其他帖子,找不到任何有助于我的内容 . 我承认承诺对我来说是一个非常混乱的话题 . 任何帮助都会很棒 . 最后,我想将每个图像URL推送到this.pics数组中,然后在页面上显示它们 . 再一次,任何帮助都会很棒 .
1 回答
除非使用箭头表示法,否则不能使用
this
来引用函数范围内的vm实例,如下所示: