简体   繁体   中英

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. It works normally but after the component is loaded the Loading component does not leave.

Here is my router.js code:

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:

<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 }],
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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