在 Vue 3 中将数据对象设置为 Promise 中的值

ril*_*ner 6 promise vue.js vuejs3

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

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

维埃

<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();
        }
}
Run Code Online (Sandbox Code Playgroud)

我收到的错误说

未捕获(承诺中)类型错误:无法设置未定义的属性“帖子”

在参照this.posts = ...

Sat*_*hak 8

thiswindow在使用dynamic范围时获取参考,使用lexical scope bindingget thisasVue

对于您的具体参考和渴望阅读有关作用域的更多信息 - 请遵循此静态(词法)作用域与动态作用域(伪代码)

用于词法绑定使用arrow-function

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