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>
enter image description here
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 :
<Suspense timeout="0">
<component :is="component[index]"></component>
<template #fallback>
<div>Loading...</div>
</template>
</Suspense>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With