"Embracing Dynamism: Enhancing Vue3 with Dynamic Routing for

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.

  1. 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

  1. 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>

Answer №1

location.pathname isn't typically meant to be directly accessed within Vue router. It's best not to access it when the route component is resolved because the location hasn't changed yet.

A dynamic component can be enclosed within another component:

  {
    path: "/semanux/form/:id",
    component: FormWrapperPage,
  },

The wrapper component would look something like this:

<component :is="PageComp"/>

...

const route = useRoute();
const PageComp = ref();

watch(
  () => route.params.id,
  async id => {
    try {
      PageComp.value = (await import("../pages/" + id + ".vue")).default
    } catch {
       router.push('/404')
    }
  },
  { immediate: true }
)

Because the dynamic component is rendered after navigation, any missing components must be managed manually.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The functionality of AJAX is hindered in the browser when attempting to fetch data from a URL

Lately, I've been encountering a strange issue when trying to fetch data from a URL. $.ajax({ url: 'URLHERE', dataType: 'html', success: function(data) { //function 2 var xml = $.parseXML(data) $(xml).find('StopLoca ...

The ul cannot be hidden if there are no li elements within it

Currently, I am attempting to hide the unordered list (ul) on a specific page using AJAX due to certain sections of the site being Ajax-based. <ul class="sub-nav-20-m" id="filtersList_m"> </ul> Below is the code that I hav ...

Enable the button if at least one checkbox has been selected

I've written some code similar to this: $('input[type=checkbox]').click(function(event) { $('.chuis').each(function() { if(this.checked) { $('#delete_all_vm').prop("disabled",false); } ...

Is it possible for Typescript to resolve a json file?

Is it possible to import a JSON file without specifying the extension in typescript? For instance, if I have a file named file.json, and this is my TypeScript code: import jsonData from './file'. However, I am encountering an error: [ts] Cannot ...

Incorporate React into current Node express application by utilizing a content delivery network (CD

I'm currently in the process of developing a web application utilizing both Node and React. Instead of having separate Node and React applications, I decided to integrate React directly into my existing setup. To achieve this, I attempted importing th ...

Different approach to iterating through elements

Looking to implement .forEach instead of a traditional for loop? 'use strict'; var score = (function(){ function updateScore() { for(var i = 0; i < arguments.length; i++) { this.score += arguments[i]; ...

Find the sum of values in an array of objects if they are identical

[{ingName: "milk", quantity: "1.5", unit: "cups"}, {ingName: "sugar", quantity: "0.25", unit: "cups"}, {ingName: "vanilla extract", quantity: "1.0", unit: "tsp&quo ...

How to disable React Native yellow warnings in console using npm

Is there a way to get rid of those pesky yellow warnings flooding my npm console? It's becoming impossible to spot my own console.log messages amidst all the warning clutter. https://i.stack.imgur.com/JAMEa.jpg I've already attempted the follow ...

What is the easiest way to retrieve a basic date with the month represented by a numerical

Struggling to retrieve the date in the format "Oct 29". I attempted using split but it varies every day. This is what I've come up with so far. let currentDate = new Date().toLocaleDateString('en-US', { month: 'short', day: 'n ...

Struggling with mapping through a multidimensional array?

I'm facing an issue with using .map() on a nested array. I initially tried to iterate through my stored data using .map(), and then attempted another iteration within the first one to handle the nested array, but it didn't work as expected. The ...

VeeValidate 4: Analyzing Field Validation Status

Trying to replicate the style of Bootstrap form validation using Vue and Vee-validate has been a challenge for me. To achieve the Bootstrap validation error message behavior, it's crucial that the input displays the class is-invalid when there is a v ...

As I embark on building my web application using next.js, I begin by importing firebase from the "firebase" package. Unfortunately, a particular error unexpectedly surfaces in the terminal

I am currently developing a next.js web application and I have decided to utilize firebase for both database management and authentication. However, when attempting to import firebase in a specific file, I encountered the following error: Error - ./firebas ...

Show the React component upon clicking the Add button

I recently developed a React component that reveals a new section whenever the user clicks the "New Section" button. However, I have encountered an issue - I would like the component to display multiple sections based on how many times the button is clic ...

Functionality fails to load correctly post completion of AJAX request

After successfully implementing an API call to OS Maps (UK map builder) as per their documentation, I encountered a problem when trying to display a map based on a custom field name using ACF (Advanced Custom Fields) in WordPress. The issue arises because ...

What is the reason for the square brackets in my json data?

My current project involves exploring the usage of JSON in conjunction with jQuery and MVC2. My goal is to generate JSON data for an AJAX post request to my controller. I have created an array using the following function: function getArguments() { var ar ...

I'm having trouble understanding why I am not receiving any response with the "form.submit()" function inside xhr.onreadystatechange() in JavaScript/AJAX

When I try to use the form.submit() function in response to xhr.onreadystatechange, it doesn't work as expected. Below is my login form: <form action="user_home.php" method="post" id="loginForm" > <tr> <td colspan=2>Members ...

The useEffect hook is able to fetch data even when the state stored in the dependency array remains constant

I have been working on developing a quiz page that utilizes the useEffect hook to fetch data. The data retrieved includes the question as well as multiple-choice options. There is a button labeled Check Answer which, when clicked, reveals the user's f ...

What purpose do controller.$viewValue and controller.$modelValue serve in the Angular framework?

I'm confused about the connection between scope.ngModel and controller.$viewValue/controller.$modelValue/controller.$setViewValue(). I'm specifically unsure of the purpose of the latter three. Take a look at this jsfiddle: <input type="text" ...

Utilizing component data in Vue.js to configure the router-link attribute

Is there a way to pass component data in <router-link to="...">? Here's an example: var data = { files: [{ name: "test", path: "/test" }] }; var component = { data: function() { return data; ...

Converting JSON information into a JavaScript array of objects

I have a JSON file containing placeholder articles for testing purposes. I'm using jQuery to parse the data from the JSON file and create an array of objects with the retrieved information. Take a look at my JSON file: { "news": [ { ...