为什么我在 Vue.js 3 中使用 async setup() 时得到空白(空)内容?
Why did I get blank (empty) content when I used async setup() in Vue.js 3?
问题
我在 Vue.js 3 中使用了 async setup(),但我的 HTML 内容消失了。我的组件模板没有插入到 HTML,但是当我删除 async 和 await 前缀时,我的 HTML 内容又回来了。我该如何解决这个问题?
async setup () {
const data = ref(null)
try {
const res = await fetch('api')
data.value = res.json()
}
catch (e) {
console.error(e)
}
return {
data
}
}
我试过了
- 我检查了 fetch,它返回了正确的响应
- 我试过
<Suspense>
标签,但还是一样的问题
您的组件 async setup()
除了缺失的 await res.json()
看起来还不错,这仍然不会导致您看到的问题。我怀疑你对 <Suspense>
的用法不正确。
要在组件中使用 async setup()
,父组件必须在 <Suspense>
标记中使用该组件:
<!-- Parent.vue -->
<template>
<Suspense>
<MyAsyncComponent />
</Suspense>
</template>
您还可以使用 <Suspense>
的 default
和 fallback
插槽在等待子组件的设置解析时显示加载指示器:
<!-- Parent.vue -->
<template>
<Suspense>
<template #default>
<MyAsyncComponent />
</template>
<template #fallback>
<span>Loading...</span>
</template>
</Suspense>
</template>
文件parent.vue
<template>
<!-- parent add <suspense> -->
<suspense>
<child />
</suspense>
</template>
<script>
import Child from './child.vue'
export default {
components: {
child
},
setup() {
return {}
}
}
</script>
文件child.vue
<template>
<div>child</div>
</template>
<script>
export default {
async setup() {
return {}
}
}
</script>
对于 child.vue
,使用 async setup...
。对于 parent.vue
,您需要将 <suspense>
添加到 child.vue
。
问题
我在 Vue.js 3 中使用了 async setup(),但我的 HTML 内容消失了。我的组件模板没有插入到 HTML,但是当我删除 async 和 await 前缀时,我的 HTML 内容又回来了。我该如何解决这个问题?
async setup () {
const data = ref(null)
try {
const res = await fetch('api')
data.value = res.json()
}
catch (e) {
console.error(e)
}
return {
data
}
}
我试过了
- 我检查了 fetch,它返回了正确的响应
- 我试过
<Suspense>
标签,但还是一样的问题
您的组件 async setup()
除了缺失的 await res.json()
看起来还不错,这仍然不会导致您看到的问题。我怀疑你对 <Suspense>
的用法不正确。
要在组件中使用 async setup()
,父组件必须在 <Suspense>
标记中使用该组件:
<!-- Parent.vue -->
<template>
<Suspense>
<MyAsyncComponent />
</Suspense>
</template>
您还可以使用 <Suspense>
的 default
和 fallback
插槽在等待子组件的设置解析时显示加载指示器:
<!-- Parent.vue -->
<template>
<Suspense>
<template #default>
<MyAsyncComponent />
</template>
<template #fallback>
<span>Loading...</span>
</template>
</Suspense>
</template>
文件parent.vue
<template>
<!-- parent add <suspense> -->
<suspense>
<child />
</suspense>
</template>
<script>
import Child from './child.vue'
export default {
components: {
child
},
setup() {
return {}
}
}
</script>
文件child.vue
<template>
<div>child</div>
</template>
<script>
export default {
async setup() {
return {}
}
}
</script>
对于 child.vue
,使用 async setup...
。对于 parent.vue
,您需要将 <suspense>
添加到 child.vue
。