5

我正在尝试将实例中的值设置data()Vuemongodb 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();
        }
}

我收到的错误说

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

在参照this.posts = ...

4

1 回答 1

6

thiswindow在使用dynamic范围时获取参考,使用lexical scope binding获取thisVue

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

用于词法绑定使用arrow-function

loadPosts() {
  stories = getPosts(); 
  stories.then(response => {
      this.posts = response.posts;
      console.log(response.posts[0].title); // "My Post Title"
  });
 }
于 2019-11-19T04:50:24.687 回答