我在带有路由器视图Vue3中使用async setup()时出现空白

cbeh67ev  于 2022-11-25  发布在  Vue.js
关注(0)|答案(2)|浏览(130)

当我在Vue 3中使用async setup ()时,我的组件消失了。为什么我在Vue3中使用async setup()时会出现空白...它工作正常,但当我使用router-view时却出现空白页。

<template>
    <div v-if="error">{{error}}</div>
    <Suspense>
        <template #default>
            <router-view></router-view>
        </template>
        <template #fallback>
            <Loading />
        </template>
    </Suspense>
</template>

<script>
import Loading from "./components/Loading"
import { ref, onErrorCaptured } from "vue"

export default {
    name: 'App',
    components: { Loading },
    setup() {
        const error = ref(null)
        onErrorCaptured(e => {
            error.value = e
        })
    }
}
</script>
  • 主文件名.js:*
import { createApp } from 'vue'
import router from "./router"
import App from './App.vue'

createApp(App).use(router).mount('#app')

当我用我的一个组件替换router-view时,它就出现了。

  • 路由器:*
import { createWebHistory, createRouter } from "vue-router";
import Portfolio from "@/views/Portfolio.vue";
import Blog from "@/views/Blog/Blog.vue";
import Detail from "@/views/Blog/Detail.vue";
import NotFound from "@/views/NotFound.vue";

const routes = [
    {
        path: "/",
        name: "Home",
        component: Portfolio,
    },
    {
        path: "/blog",
        name: "blog",
        component: Blog,
    },
    {
        path: "/blog/:slug",
        name: "detail",
        component: Detail,
    },
    {
        path: "/:catchAll(.*)",
        component: NotFound,
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

export default router;
ars1skjm

ars1skjm1#

<Suspense>的默认模板应该包含一个 *async组件 *(即一个带有async setup()的组件),但您却将<router-view>放在了那里。
您必须将<Suspense>重构到它自己的包含异步组件的 Package 器组件(例如HomeView.vue)中,将<router-view>本身保留在App中:

<!-- App.vue -->
<template>
  <router-view />
</template>

<!-- HomeView.vue -->
<template>
  <Suspense>
    <template #default>
      <MyAsyncComponent />
    </template>
    <template #fallback>
      <Loading />
    </template>
  </Suspense>
</template>

然后更新路由器配置以使用该 Package 器:

const routes = [
  {
    path: '/'
    name: 'Home',
    component: HomeView
  },
  //...
]
nhaq1z21

nhaq1z212#

Vue文档中有一个示例,说明如何将<Suspense>与其他组件一起使用

<RouterView v-slot="{ Component }">
  <template v-if="Component">
    <Transition mode="out-in">
      <KeepAlive>
        <Suspense>
          <!-- main content -->
          <component :is="Component"></component>

          <!-- loading state -->
          <template #fallback>
            Loading...
          </template>
        </Suspense>
      </KeepAlive>
    </Transition>
  </template>
</RouterView>

参考:https://vuejs.org/guide/built-ins/suspense.html#combining-with-other-components

相关问题