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