【问题标题】:how to use suspense and dynamic components in vue3vue3中如何使用悬念和动态组件
【发布时间】:2022-10-19 23:26:15
【问题描述】:

悬念中,我异步导入了四个不同的组件。当我点击按钮切换的时候,发现有悬念的loading slot只会在第一次显示,但是再次切换时就不行了。如何解决这个问题呢? Suspense 不支持与动态路由一起使用吗?

<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

【问题讨论】:

    标签: vue.js vue-component vuejs3


    【解决方案1】:

    默认情况下,当 Suspense 已解决时,如果根组件发生更改,它不会显示回退内容。如果组件在超时之前未呈现,您可以使用 Suspense 的 timeout 属性使其显示回退内容。

    在您的情况下,超时 0 将确保在动态组件更改时立即显示回退内容:

    <Suspense timeout="0">
        <component :is="component[index]"></component>
        <template #fallback>
            <div>Loading...</div>
        </template>
    </Suspense>
    

    【讨论】:

      猜你喜欢
      • 2022-11-05
      • 2021-05-03
      • 1970-01-01
      • 2021-04-15
      • 2022-01-25
      • 2021-10-30
      • 2021-04-27
      • 1970-01-01
      • 2020-08-13
      相关资源
      最近更新 更多