【问题标题】:Set data object to value from Promise in Vue 3在 Vue 3 中将数据对象设置为来自 Promise 的值
【发布时间】:2020-03-14 12:59:37
【问题描述】:

我正在尝试将Vue 实例中的data() 值设置为从mongodb api 调用返回的Promise 检索到的值。我能够检索我正在尝试实现的数据,但是我很难在 data() 字段中使用它,以便我可以在模板中访问它。

我从vue2 找到的一些解决方案在这种情况下似乎不起作用。提前致谢。

Vue

<template>
  <Article :title=posts[0].title></Article>  // Another Vue component
</template>

let stories;

export default {
       data() {
            return {
                posts: {}
            }
       },
        methods: {
            loadPosts() {
                stories = getPosts(); // makes an api request to a mongodb that returns a Promise
                stories.then(function(response) {
                    this.posts = response.posts;
                    console.log(response.posts[0].title); // "My Post Title"
                });

            }
        },
        mounted() {
            this.loadPosts();
        }
}

我收到的错误是

Uncaught (in promise) TypeError: Cannot set property 'posts' of undefined

参考this.posts = ...

【问题讨论】:

    标签: vue.js promise vuejs3


    【解决方案1】:

    this 在使用dynamic 范围时获取window 引用,使用lexical scope binding 获取this 作为Vue

    为了您的具体参考和渴望阅读有关范围的更多信息 - 请关注此Static (Lexical) Scoping vs Dynamic Scoping (Pseudocode)

    对于词法绑定使用arrow-function

    loadPosts() {
      stories = getPosts(); 
      stories.then(response => {
          this.posts = response.posts;
          console.log(response.posts[0].title); // "My Post Title"
      });
     }
    

    【讨论】:

      猜你喜欢
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-02
      • 2021-11-13
      • 1970-01-01
      相关资源
      最近更新 更多