在 Vue 组件中等待异步结果的正确方法



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

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

商店.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>

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

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

最新更新