Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'd like to conditionnaly import a component in the vue router. Here is what I have for the moment:

children: [
  {
    path: ':option',
    component: () => import('../components/Option1.vue'),
  },
],

Depending on what :option is, I want to import a different component (Option1.vue, Option2.vue, etc.). I know I could put several children but i actually need the option variable in my parent component (I make tests if the route has an option).

How would it be possible to do that? Thanks in advance :)

question from:https://stackoverflow.com/questions/65928787/conditionally-import-a-component-in-vue-router

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
794 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can create a loader component containing a dynamic component instead of doing conditional routing. In the loader, you'll conditionally lazy load the option component based on the route param. Not only is this easier when routing, you also don't have to manually import anything, and only options that are used will be imported.

Step 1. Route to the option loader component

router

{
  path: ':option',
  component: () => import('../components/OptionLoader.vue'),
}

Step 2. In that option loader template, use a dynamic component which will be determined by a computed called optionComponent:

OptionLoader.vue

<template>
  <component :is="optionComponent" />
</template>

Step 3. Create a computed that lazy loads the current option

OptionLoader.vue

export default {
  computed: {
    optionComponent() {
      return () => import(`@/components/Option${this.$route.params.option}.vue`);
    }
  }
}

This will load the component called "Option5.vue", for example, when the option route param is 5. Now you have a lazy loaded option loader and didn't have to manually import each option.


Edit: OP has now indicated that he's using Vue 3.

Vue 3

For Vue 3, change the computed to use defineAsyncComponent:

OptionsLoader.vue

import { defineAsyncComponent } from "vue";
computed: {
  optionComponent() {
    return defineAsyncComponent(() =>
      import(`@/components/Option${this.$route.params.option}.vue`)
    );
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...