0

I have components in several folders. Let's say I have:

.components
..folder1
...component1.vue
...component2.vue
..folder2
...component1.vue
...component2.vue

I'd like my app to search the components dynamically depending on the route, for example:

{ path: '/component1/:typeOfComponent/:param', component: () => import('./components/' + $route.params.typeOfComponent + '/component1.vue') }

I know I can pass all the props (it works correctly), but I'd like to get the good component directly with routing. Is there a way to do that?

Thanks in advance :)

1 Answer 1

2

You can use Dynamic component combined it with route params.

your components directory:

  1. /components/ComponentOne.vue
  2. /components/ComponentTwo.vue

your router

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home
  },
  { // this route will receive a component name as a parameter
    path: "/about/:component",
    name: "About",
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/About.vue"),
    params: true
  }
];

In your views/About.vue

<template>
  <div class="about">
    <h1>This is About Page</h1>
    <component :is="$route.params.component"></component>
  </div>
</template>

<script>
// @ is an alias to /src

import ComponentOne from "@/components/ComponentOne.vue";
import ComponentTwo from "@/components/ComponentTwo.vue";

export default {
  name: "Home",
  components: {
    ComponentOne,
    ComponentTwo
  }
};
</script>

when you navigate to url:8080/about/ComponentTwo the about page will show componentTwo.vue


If you dont want to import every component

one option is to create a src/globalComponent.js file and import every global components in that file.

import Vue from "vue";

Vue.component("ComponentOne", () => import("@/components/ComponentOne.vue"));
Vue.component("ComponentTwo", () => import("@/components/ComponentTwo.vue"));

then import to src/main.js

import Vue from "vue";
import App from "./App.vue";
import router from "./router";

import "./globalComponents";

Vue.config.productionTip = false;

new Vue({
  router,
  render: h => h(App)
}).$mount("#app");
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Indeed, that's a good way to do it. Is there another without having to import every component?
@djcaesar9114 I have updated my answer. one option is to make your components global.
Thanks a lot Evan, your answer helped me a lot to simplify my project.

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.