【问题标题】:Correct way of waiting for async result in Vue componentVue组件中等待异步结果的正确方法
【发布时间】:2020-02-09 16:15:42
【问题描述】:

我想知道在等待承诺结果的生命周期中放在哪里。可运行的样本在那里:https://codesandbox.io/s/focused-surf-migyw。我在created() 中创建了一个Promise 并在async mounted() 中等待结果。这是对 Vue 组件生命周期的正确和最佳使用吗?

PS 我不想将结果作为突变存储在商店中,因为我可以多次调用此方法。因此我返回Promise。它从 REST 端点下载用户详细信息。

store.js

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  actions: {
    FETCH_PROFILE: async context => {
      const profile = { name: "Leos" };
      return new Promise(function(resolve, reject) {
        window.setTimeout(function() {
          resolve(profile);
        }, 2000);
      });
    }
  }
});

组件.vue

<template>
  <div class="hello">
    <p>Name = {{this.userProfile.name}}</p>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data: () => ({
    userProfile: null,
    profilePromise: null
  }),
  created() {
    this.profilePromise = this.$store.dispatch("FETCH_PROFILE");
    console.log(`my profile: ${this.userProfile}`);
  },
  async mounted() {
    const response = await this.profilePromise;
    console.log(response);
    this.userProfile = response;
  }
};
</script>

【问题讨论】:

  • 它是const response = await this.$store.dispatch("FETCH_PROFILE")。不需要created
  • 除非您有非常令人信服的理由将其分解为同时使用createdmounted,否则在async created 中完成所有操作会更有意义。 (mounted 通常用于 DOM 操作。)只需 const response = await this.$store.dispatch("FETCH_PROFILE"); this.userProfile = response
  • 我认为早点启动它可能会节省一些毫秒
  • 不,如果有的话,双向速度应该相等,只是解释代码所花费的时间。 (无论如何,我们可能谈论的是几分之一纳秒而不是毫秒)。您不必担心这会推迟挂载,因为异步调用是非阻塞的。
  • 挂载中的异步/等待是等待结果的正确方式吗?

标签: javascript vue.js vuejs2 async-await vuex


【解决方案1】:

除非您有非常令人信服的理由将其分解为同时使用createdmounted,否则在created 中执行所有操作会更有意义。您不必担心这会推迟挂载,因为异步调用是非阻塞的。使用created 而不是mounted,这通常用于DOM 操作或DOM 敏感操作。

async created() {
  const response = await this.$store.dispatch("FETCH_PROFILE");
  this.userProfile = response;
}

【讨论】:

  • AFAIK 生命周期钩子的问题 Vue 类似于 React,即它是 SSR。异步副作用不应该在服务器端执行,但如果它们是在created 中生成的,它们就会执行。此外,async created 给人一种错误的印象,即它将在mounted 之前完成,这不是真的,我已经看到了几个共享这种误解的问题。
  • @EstusFlask - 他没有提到 SSR/Nuxt,我不知道 React,所以我无法评论这个比较。 Nuxt 也有其他的做事方式(参见asyncData)。至于那种错误的印象,我没有看到它,我不建议对边缘误解进行微优化代码,特别是考虑到这会使他的应用程序变慢并且他已经在谈论优化毫秒。也就是说,mounted 可以工作,而且没有“错误”,但我更喜欢更清晰的封装,我认为大多数 Vue 文档都会提出相同的建议。
  • 真正的挑战是找出 AWS lambda 在哪里花费了这么多时间..
猜你喜欢
  • 2020-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-26
  • 1970-01-01
  • 2019-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多