简体   繁体   English

如何延迟加载 Vue 组件?

[英]How can I lazy load a Vue Component?

I'm trying to lazy load a Login component but after using <Suspense> and <template> with default and callback.我正在尝试延迟加载登录组件,但在使用<Suspense><template>以及默认和回调之后。 It works normally but after the component is loaded the Loading component does not leave.它可以正常工作,但是在加载组件后,正在加载的组件不会离开。

Here is my router.js code:这是我的 router.js 代码:

import { createWebHistory, createRouter } from 'vue-router'


const Login = () => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(
                import ('./components/pages/auth/Login'),
            )
        }, 1000)
    })
}
const Register = () => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(
                import ('./components/pages/auth/Register'),
            )
        }, 1000)
    })
}

const routes = [{
        path: '/login',
        name: 'login',
        component: Login,
    },
    {
        path: '/register',
        name: 'register',
        component: Register,
    }
]

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

export default router

App.vue is my root component file which is shown below: App.vue 是我的根组件文件,如下所示:

<template>
    <div>
        <Suspense>
            <template #default>
                <RouterView />
            </template>
            <template #fallback>
                <div>
                    <h1>Loading....</h1>
                </div>
            </template>
        </Suspense>
    </div>
</template>
<script>
export default {
    components: {

    }
}
</script>
<style scoped>
div {
    height: 100%;
    width: 100%;
    background-color: black;
}

h1 {
    font-size: 30px;
    font-weight: bold;
    color: white;
}
</style>

Below is the result I get: The black background is the loading which is not suppose to be there after component has loaded.下面是我得到的结果:黑色背景是加载组件加载后不应该存在的加载。 Click to view picture点击查看图片

According with official docs all you need is to pass a function with dynamic import inside:根据官方文档,您只需在内部传递一个带有动态导入的函数:

// replace
// import UserDetails from './views/UserDetails'
// with
const UserDetails = () => import('./views/UserDetails')

const router = createRouter({
  // ...
  routes: [{ path: '/users/:id', component: UserDetails }],
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM