vue.jsvuejs3vue-router

Lazy Loading Routes with conditions


My routes.js is:

{...
  path: ":term",
  name: "some-name",
  component: () => import("../path/to/com.vue")
}
...

Question is: How to make smth like this and make it works:

{...
  path: ":term",
  name: "some-name",
  component: (route) => {
    if(route.term === 'spam'){
       return import("../path/to/com1.vue")
    }
    return import("../path/to/com.vue")
  }
}

Solution

  • The component in a route is only evaluated once. In other words, what you are asking for is not possible, by design.

    However, the functionality can be achieved using a dynamic loader component:

    <!-- RouteTermLoader.vue -->
    
    <script setup>
    import { defineAsyncComponent } from 'vue'
    import { useRoute } from 'vue-router'
    
    const route = useRoute()
    
    const ComponentA = defineAsyncComponent(() =>
      import('./path/to/ComponentA.vue')
    )
    
    const ComponentB = defineAsyncComponent(() => 
      import('./path/to/ComponentB.vue')
    )
    </script>
    <template>
      <ComponentA v-if="route.params.term === 'spam'" />
      <ComponentB v-else />
    </template>
    
    {
      path: ":term",
      name: "some-name",
      component: () => import("../path/to/RouteTermLoader.vue")
    }
    

    Relevant documentation here.