【发布时间】: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 = ...
【问题讨论】: