Skip to content
Advertisement

Async components Vue 2

I’m trying to use async components. Here is my configuration:

  1. Vue 2 using Single File Component approach
  2. Webpack 2
  3. Vue Router

The app is pretty basic, I have an “everyone” section contained in App and an “admin” section contained in Admin. I would like to load the component and all the .js related to the Admin if and only if I’m visiting the corresponding route.

After reading the vue-router docs on Lazy Loading, and the one of Vue2 on async components, I’m still not sure how to do that especially with the Single File Component approach.

Here is what I did for the moment but I don’t know if it is ok since in the documentation of Vue2 they said :

Vue.component(
  'async-webpack-example',
  () => import('./my-async-component')
)

Also what do I have to do with webpack so it creates a chunk of everything related to Admin so that adminChunk.jsis just loaded when reaching admin route ?

What is the syntax to make a single file component a async component ?

app.js

const Admin = resolve => {
    // require.ensure is Webpack's special syntax for a code-split point.
    require.ensure(['./components/admin/Admin.vue'], () => {
        resolve(require('./components/admin/Admin.vue'))
    })
};

const routes = [
    { path: '/', component: App },
    { path: '/admin', meta: { requiresAdmin: true }, component: Admin},
];

Admin.vue

<template>
        <admin-menu></admin-menu>
        <child></child>
</template>


<script>
    import AdminMenu from './Admin-Menu.vue'
    import Child from './child.vue
    
    export default{
        data () {
        },
        components: {
            AdminMenu,
            Child,
        },
    }
</script>

Advertisement

Answer

You can pass a third parameter to the require.ensure function with the name of the chunk.

Advertisement