djcaesar9114
djcaesar9114

Reputation: 2137

How to include a route param in the component address in Vue?

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 :)

Upvotes: 0

Views: 500

Answers (1)

Evan
Evan

Reputation: 2497

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");

Upvotes: 2

Related Questions