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:
terminal├── lessons | ├── 1.vue | ├── 2.vue ├── App.vue
If you want to import the lessons dynamically, you can use defineAsyncComponent()
.
Example:
vue<template> <lesson/> </template> <script> 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`)) } } </script>
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.