如何在VUE3中使用悬念和动态组件
在悬念中,我异步地导入四个不同的组件。当我单击按钮切换时,我发现悬疑中的加载插槽只会首次显示,但是当我再次切换时它不起作用。如何解决这个问题?悬念不支持动态路由使用吗?
<template>
<div class="app">
<button @click="index = 0">1</button>
<button @click="index = 1">2</button>
<button @click="index = 2">3</button>
<button @click="index = 3">4</button>
<Suspense>
<component :is="component[index]"></component>
<template #fallback>
<div>Loading...</div>
</template>
</Suspense>
</div>
</template>
<script setup lang="ts">
import { defineAsyncComponent, ref } from 'vue'
const son1 = defineAsyncComponent(() => import('./components/son1.vue'))
const son2 = defineAsyncComponent(() => import('./components/son2.vue'))
const son3 = defineAsyncComponent(() => import('./components/son3.vue'))
const son4 = defineAsyncComponent(() => import('./components/son4.vue'))
const component = [son1, son2, son3, son4]
const index = ref(0)
</script>
<style scoped lang="less"></style>
In suspense, I import four different components asynchronously. When I click the button to switch, I find that loading slots in suspense will only be shown for the first time, but it doesn't work when I switch again. How to solve this problem? Does Suspense not support use with dynamic routing?
<template>
<div class="app">
<button @click="index = 0">1</button>
<button @click="index = 1">2</button>
<button @click="index = 2">3</button>
<button @click="index = 3">4</button>
<Suspense>
<component :is="component[index]"></component>
<template #fallback>
<div>Loading...</div>
</template>
</Suspense>
</div>
</template>
<script setup lang="ts">
import { defineAsyncComponent, ref } from 'vue'
const son1 = defineAsyncComponent(() => import('./components/son1.vue'))
const son2 = defineAsyncComponent(() => import('./components/son2.vue'))
const son3 = defineAsyncComponent(() => import('./components/son3.vue'))
const son4 = defineAsyncComponent(() => import('./components/son4.vue'))
const component = [son1, son2, son3, son4]
const index = ref(0)
</script>
<style scoped lang="less"></style>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,当悬念已解决时,如果更改了根组件,则不会显示后备内容。如果组件在超时之前没有呈现,则可以使用悬疑的超时道具使其显示后备内容。
在您的情况下,0的暂停将确保当动态组件更改时立即显示后退内容:
By default when a Suspense has been resolved it doesn't display the fallback content if the root component is changed. You can use the timeout prop of Suspense to make it display the fallback content if the component doesn't render before the timeout.
In your case a timeout of 0 will make sure that the fallback content is immediately displayed when the dynamic component changes :