To lazy-load Vue.js components, you can utilize dynamic imports along with the vue-router
library. Here's a step-by-step guide:
Make sure you have vue-router
installed. If not, run npm install vue-router
or yarn add vue-router
in your project directory.
In your main Vue.js file (usually main.js
), import vue-router
and create a router instance:
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const router = new VueRouter({
routes: [
// your routes configuration goes here
],
});
new Vue({
router,
render: (h) => h(App),
}).$mount('#app');
routes
array with lazy-loaded components using the component
key. For example:import Vue from 'vue';
import VueRouter from 'vue-router';
const HomeComponent = () => import('./components/Home.vue');
const AboutComponent = () => import('./components/About.vue');
const ContactComponent = () => import('./components/Contact.vue');
const routes = [
{ path: '/', component: HomeComponent },
{ path: '/about', component: AboutComponent },
{ path: '/contact', component: ContactComponent },
];
Vue.use(VueRouter);
const router = new VueRouter({
routes,
});
new Vue({
router,
render: (h) => h(App),
}).$mount('#app');
Home.vue
, About.vue
, Contact.vue
), export the component as usual:<template>
<!-- your component template -->
</template>
<script>
export default {
// component options go here
};
</script>
<style scoped>
/* component styles go here */
</style>
With this setup, when you navigate to a specific route, the corresponding component will be loaded lazily only when needed. The initial bundle size will be smaller, improving the application's performance.