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"
4
  • You can grab the router prams userType and load you components dynamically using v-is attribute. v2.vuejs.org/v2/guide/components-dynamic-async.html#ad Commented Feb 23, 2023 at 7: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) Commented Feb 23, 2023 at 7: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? Commented Feb 23, 2023 at 7:51
  • yes. depending on the userType the respective component should be loaded Commented Feb 23, 2023 at 7:52

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.