我正在尝试将实例中的值设置data()
为Vue
从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();
}
}
我收到的错误说
未捕获(承诺中)类型错误:无法设置未定义的属性“帖子”
在参照this.posts = ...