Seeking guidance on implementing a dynamic component with Dynamic Routing in Vue3. The goal is to render a component based on the parameter (path named id) from router.ts.
In the router.ts file, there is a dynamic parameter called id that needs to be used to render corresponding components.
For instance: When accessing http://localhost:3000/forms/form/FirstPage, it should render the FirstPage component already created in the project. Similarly, http://localhost:3000/forms/form/SecondPage should render the SecondPage component, and so forth.
The issue lies in successfully implementing this functionality. One attempt involved the following code snippet:
{
path: "/forms/form/:id",
component: () => import("../pages/" + location.pathname.slice(1) + ".vue")
},
However, this approach did not yield the desired results. Below are excerpts from my App.vue and router/index.ts files for reference.
- Snippet from router/index.ts:
import { createWebHistory, createRouter } from "vue-router"
import FirstPage from "../pages/FirstPage.vue"
import SecondPage from "../pages/SecondPage.vue"
import ThirdPage from "../pages/ThirdPage.vue"
import NotFound from "../components/NotFound.vue"
const routes = [
{
path: "/",
name: "first",
component: FirstPage
},
{
path: "/2/70",
name: "second",
component: SecondPage
},
{
path: "/3/70",
name: "third",
component: ThirdPage
},
{
path: "/forms/form/:id",
component: () => import("../pages/" + location.pathname.slice(1) + ".vue")
},
{
path: "/:catchAll(.*)",
component: NotFound
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
- Snippet from App.vue:
<template>
<router-view></router-view>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>