代码之家  ›  专栏  ›  技术社区  ›  ravenUSMC

在Vue中以承诺方式传递数据

  •  -1
  • ravenUSMC  · 技术社区  · 6 年前

    我最近开始使用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) :

    uncaught(in promise)typeerror:无法读取未定义的属性“count”

    我试着读了很多关于这件事的文章,也看了其他的帖子,却找不到任何对我有帮助的东西。我承认,对我来说,承诺是一个非常令人困惑的话题。任何帮助都会很好的。最后,我希望将每个图像url推入this.pics数组,然后在页面上显示它们。再说一遍,任何帮助都会很好的。

    1 回复  |  直到 6 年前
        1
  •  0
  •   piscator    6 年前

    你不能用 this 要引用函数范围内的vm实例,除非使用箭头符号,如下所示:

    pexelsClient.getPopularPhotos(10, 1)
        .then((result) => {
        console.log(this.count) 
    }