1

I have a base component that is extended by some other Components as follows:

// UserForm
<template>
    <div class="user-form"></div>
</template>

// AdministratorForm
<template>
    <UserForm v-model="administrator">
        // additional fields
    </UserForm>
</template>

Now I want to set up a dynamic route where the component is selected by a parameter:

{
   path: '/users/:userTyp/:programId',
   name: 'user-create',
   component: () => import('@/modules/users/forms/'+ userTyp+ 'FormPage.vue'),
   props: (route: any) => ({
       programId: route.params.programId
   })
}

Is there any way to have that dynamic routing and when, and how?

I use the following versions:

  • "vue": "^2.6.11",
  • "vue-router": "^3.2.0"
Neha Soni
  • 3,935
  • 2
  • 10
  • 32
SNO
  • 793
  • 1
  • 10
  • 30
  • You can grab the router prams userType and load you components dynamically using v-is attribute. https://v2.vuejs.org/v2/guide/components-dynamic-async.html#ad – Dipo Ahmed Feb 23 '23 at 07:45
  • can you pleace give me an example? The aim is to add a new inherited component withoud need to add is anywhere (in routes or any other component) – SNO Feb 23 '23 at 07:49
  • I am not clear on what you are trying to do. Are you trying to load AdminStratorForm or other similar components based on the userType? – Dipo Ahmed Feb 23 '23 at 07:51
  • yes. depending on the userType the respective component should be loaded – SNO Feb 23 '23 at 07:52

1 Answers1

3

Instead of trying to import the components in the router definition, you can dynamically import the components in Vue files. One way is using :is attribute but it still contains unnecessary import of components. The better approach could be to use dynamic imports from Webpack with the computed property.

What you can do is, give a component to your route-

{
   path: '/users/:userTyp/:programId',
   name: 'user-create',
   component: () => import('@/modules/SomeComponent.vue'),
}

And in that SomeComponent.vue, you can import the components dynamically based on the route params-

<template>
  <component v-bind:is="myComponent"></component>
</tamplarte>
computed: {
  myComponent() {
    let data = this.$route.params.userTyp;
    return () => import(`@/modules/users/forms/${data}/FormPage.vue`);
  }
},

Hope it helps.

Neha Soni
  • 3,935
  • 2
  • 10
  • 32