【问题标题】:Passing data in a promise in vue在 vue 中通过 Promise 传递数据
【发布时间】:2019-05-10 04:42:14
【问题描述】:

我最近开始使用 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: Cannot read property 'count' of undefined

我已尝试阅读有关此问题的大量文章并查看其他帖子,但找不到任何对我有帮助的内容。我承认承诺对我来说是一个非常令人困惑的话题。任何帮助都会很棒。最终,我想将每个图像 URL 推送到 this.pics 数组中,然后将它们显示在页面上。同样,任何帮助都会很棒。

【问题讨论】:

标签: javascript vue.js callback promise vuejs2


【解决方案1】:

你不能使用this来引用函数范围内的vm实例,除非你使用箭头符号,像这样:

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

【讨论】:

    猜你喜欢
    • 2018-10-12
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2018-12-17
    • 2020-03-14
    • 2021-04-17
    相关资源
    最近更新 更多