Vue 导出导入异步等待停止

Vue export import async await stops

我使用 Vue 并在 load.js 中有一个方法。

async function loadTask(x) {
  return await x; // Some async code
}

export { loadTask };

在我调用的 Vue 组件中,await 阻止 <template> 加载。没有 await,下面的代码运行。我想念什么?

<script setup>
import { loadTask } from './methods/load.js';
const test = loadTask(3);
console.log(await test);
</script>
<template>
  <div>Does not run</div>
</template>

根据文档:

async setup() must be used in combination with Suspense, which is currently still an experimental feature. We plan to finalize and document it in a future release - but if you are curious now, you can refer to its tests (opens new window)to see how it works.

https://v3.vuejs.org/api/sfc-script-setup.html#top-level-await

https://v3.vuejs.org/guide/migration/suspense.html#suspense

因此,如果您有异步设置,则必须像这样在父级中导入此组件:

import { defineAsyncComponent } from "vue";

export default {
  components: {
    HelloWorld: defineAsyncComponent(() =>
      import("./components/HelloWorld.vue")
    ),
  },
};
</script>

并在悬念包裹的模板中使用它:

<template>
  <suspense>
    <template #default>
      <HelloWorld />
    </template>
    <template #fallback>
      <div>Loading...</div>
    </template>
  </suspense>
</template>

演示:

https://codesandbox.io/s/reverent-sinoussi-9r5or?file=/src/components/HelloWorld.vue

所述, 如果您不需要异步组件和 Suspense 的全部功能,您可以使用 onBeforeMount:

const test = ref('');
onBeforeMount(async () => {
  test.value = await loadTask(3);
  console.log(test.value);
})

或者在 async 函数中进行初始化,您调用时没有 await 完成承诺:

const test = ref('');
const init = async () => {
  test.value = await loadTask(3);
  console.log(test.value);
}
init();

或使用 promise chainig:

const test = ref('');
loadTask(3).then(task => {
  test.value = task;
  console.log(test.value);
});

您还需要针对每种情况适当地处理错误。