vue.js - 在 Vue 3 中将数据对象设置为来自 Promise 的值

标签 vue.js promise vuejs3

我正在尝试设置 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获取 thisVue
对于您的具体引用和渴望阅读更多关于范围的信息 - 请关注 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/

相关文章:

javascript - 将组件作为字符串存储在变量中并在 Vue JS 中通过变量渲染它

javascript - 如何在 Parse.com CloudCode 上创建自定义帮助器模块以与 then() Promise 一起使用?类型错误 : Cannot call method 'then' of undefined

typescript - 在该组件的其余部分找不到 Vue3 设置返回值

javascript - Flowbite 不适用于组件,但适用于根

javascript - Vue 3 : computed property doesn't track its dependency in composition API

javascript - 如何将 webpack 与静态图像文件一起使用?

javascript - 过滤自定义 JSON

vue.js - Nuxt.js - 谷歌分析设置不跟踪任何事件

javascript - 使用 async/await 可能出现未处理的 Promise 拒绝

javascript - fetch res.json 继续返回 Unresolved promise