我正在尝试设置 data()
Vue
中的值实例为从 mongodb api
返回的 Promise 检索到的值称呼。我能够检索我正在尝试实现的数据,但是我正在努力在 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();
}
}
我收到的错误说
Uncaught (in promise) TypeError: Cannot set property 'posts' of undefined
引用
this.posts = ...
最佳答案
this
获取 window
使用时引用 dynamic
范围,使用 lexical scope binding
获取 this
如Vue
对于您的具体引用和渴望阅读更多关于范围的信息 - 请关注 Static (Lexical) Scoping vs Dynamic Scoping (Pseudocode)
对于词法绑定(bind)使用 arrow-function
loadPosts() {
stories = getPosts();
stories.then(response => {
this.posts = response.posts;
console.log(response.posts[0].title); // "My Post Title"
});
}
关于vue.js - 在 Vue 3 中将数据对象设置为来自 Promise 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58926739/