Dynamic import in Vue

Let's assume that you need to import a component dynamically depending on the current URL.

For example, let's assume that the you've the following folder structure:

├── lessons
|   ├── 1.vue
|   ├── 2.vue
├── App.vue

If you want to import the lessons dynamically, you can use defineAsyncComponent().



import { defineAsyncComponent } from 'vue'

// Assume that the URL is /lessons/1
var num = window.location.href.split('/').pop()

export default {
    name: 'App',
    components: {
        lesson: defineAsyncComponent(() => import(`./lessons/${num}.vue`))


Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.