Creating components and dynamic routing based on the current route

I'm in the process of creating "overview" pages for different sections within my app, each triggered from the root of that particular section.

For example, localhost/hi should display the HiOverview component,

And localhost/he should display the HeOverview component. Since there are multiple sections like this, I want to avoid assigning components to constants and reusing them across routes. Instead, I aim to handle everything dynamically within a single route.

However, I'm facing challenges with creating the Components in the beforeEnter hook. Each route object expects a component, but I simply want to determine the component based on the route. (The sectionsWithOverview array contains the names of routes where an overview is required).

const router = new Router({
  linkActiveClass: 'active',
  mode: 'history',
  routes: [
    { path: '/:section',
      component: Placeholder,
      beforeEnter: (to, from, next) => {
        const section = to.params.section

        if (sectionsWithOverview.includes(to.params.section)) {
          next({ name: `${to.params.section}Overview` })
        } else {
          next()
        }
      },
}

Can anyone provide assistance? How can I conditionally assign a component onBeforeEnter and then route to that specific Component? It currently works when I declare each SectionOverview beforehand, but that defeats the purpose of my approach.

Thank you for any guidance :)

Answer №1

I implemented something similar in a recent project, but instead of using beforeRouteUpdate I took a different approach.

This is how I set it up: In my route.js file, I defined the dynamic routes like this

const router = new Router({
  linkActiveClass: 'active',
  mode: 'history',
  routes: [
    { 
      path: '/:section',
      component: Placeholder,
      name: 'placeholder'
    },
}

Then, in my component (let's say Placeholder.vue), I added the following line of code to my HTML

<transition name="fade" mode="out-in">
    <component :is="section" key="section"></component>
</transition>

Next, in my JavaScript file, I utilized the beforeRouteUpdate hook and specified all the components corresponding to the route sections.

import he from './heOverview.vue'
import hi from './hiOverview.vue'

beforeRouteUpdate (to, from, next) {
  // Update section based on params
  this.section = to.params.section
  next()
},
components: {
  he,
  hi
},
data () {
  return {
    section: ''
  }
}

Now, when a user navigates to localhost/he, the heOverview.vue component will be displayed. Just ensure that the value of the section parameter corresponds to a valid view, otherwise an error may occur.

If you want more details on how this setup works, check out these resources: Vue Components - Dynamic & Async Vue Router - Navigation Guards

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

Troubleshooting the Height Problem in Material-UI's Menu

I am trying to make the menu height responsive by setting it equal to the window height using CSS. I want the menu height to increase as the page length increases due to added elements. I have attempted using "height:100%" and "height: 100vh" in the styles ...

Guide to extracting information from a Node.js http get call

I am currently working on a function to handle http get requests, but I keep running into issues where my data seems to disappear. Since I am relatively new to Node.js, I would greatly appreciate any assistance. function fetchData(){ var http = requir ...

Unable to retrieve event data and integrate it into HTML using jQuery

Just starting out with leaflet and JavaScript, jQuery. I've got an index.html page displaying a map, and want to show the coordinates of the mouse pointer underneath the map when it moves. To achieve this, I have a div element with the id "coordinat ...

Submitting data from a JavaScript frontend to a PHP backend

I've exhausted all options in attempting to resolve this issue. The javascript code is designed to send a list of product IDs to a PHP page. When products are selected, the submit button should activate the submit function. function submit() { ...

What steps can I take to make my animation work in the opposite direction as well?

I'm currently working with an angular slider that is set to TRUE/OPEN by default. The issue I am facing is that while I am able to slide it using angular animations in one direction, I am unable to see the transition when sliding it back. Any assistan ...

Combining Django with the powerful Vue3 and lightning fast Vite

I'm in the process of upgrading my multipage app from Vue2 with webpack to Vue3 with Vite. After successfully rendering my Vue3 components on my Django templates, I am now facing a challenge - setting component variables on the Vue app using the Djan ...

What is the best way to save the output of an asynchronous function into a class attribute?

Currently, I am attempting to retrieve HTML content from a webpage by utilizing a class equipped with a single asynchronous method. This process involves Typescript 3.4.3 and request-promise 4.2.4. import * as rp from 'request-promise'; class H ...

Managing stream pauses and resumes in Node.js using setTimeout()

After some experimentation with Node.js (v4.4.7), I managed to create a simple program to play a sound... const Speaker = require('audio-speaker/stream'); const Generator = require('audio-generator/stream'); const speaker = new Speake ...

Searching and updating a value in an array using JavaScript

I need help solving a Javascript issue I'm facing. I'm working on an e-commerce project built in Vue, and I want to implement the selection of product variants on the client-side. The data format being sent to the backend looks like this: { & ...

Is the process.env variable used universally for environmental variables, or is it specifically designed for use in Node.js

Can process.env function as a universal environment variable or is it exclusive to NodeJs? https://nodejs.org/dist/latest-v8.x/docs/api/process.html#process_process_env Instructions on setting it using the node command are provided: $ node -e 'proc ...

Toggle the input box by clicking the button

How do I show or hide the input box (blue square) when I click the search button (red square)? Link Image I attempted to create the transition in CSS and also experimented with JavaScript, but the JavaScript part confused me. Here is what I tried: $(" ...

Utilize the Jest moduleNameMapper for locating files: "resolver": undefined

Among the various files I have, there is a text file located in the component directory within the path: src/components/text Despite this, Jest is unable to locate the file when utilizing the webpack alias import Text from "components/text"; I ...

Tips for implementing fluid transitions between mouse X and Y coordinates using JavaScript

I recently developed a function that enables a DOM element to follow the mouse cursor. You can check out the code here. Currently, I am looking for suggestions on how to add a nice animation to this feature. Ideally, I want to incorporate a slight delay w ...

Navigating through directory paths in JavaScript can be a daunting task for many

In my app.js file, I've included the following code: app.use(multer({dest:'./uploads'})) What does './uploads' refer to here? It is located in the same directory as app.js. In what way does it differ from simply using uploads? I ...

Dynamically loading an AngularJS controller

I am faced with the challenge of integrating an Angular app with dynamically loaded controllers into an existing webpage. Below is a code snippet where I have attempted to achieve this based on my understanding of the API and some research: // Create mod ...

What is the best way to create shared scope and transmit data within an Angular directive?

In my angular directive, I have the following code: app.directive('myDir', function () { return { restrict: 'E', scope: true, template:'<div>{{myindex}}</div>', link: function(scope, element, att ...

How can I iterate through JSON data and showcase it on an HTML page?

I am in the process of developing a weather application using The Weather API. So far, I have successfully retrieved the necessary data from the JSON and presented it in HTML format. My next goal is to extract hourly weather information from the JSON and ...

Acquire Laravel notification data through the power of AJAX

I successfully implemented a notification feature in Laravel, and it was working perfectly. However, I encountered an issue when trying to display the notification details in a dynamic modal upon clicking on the notification. I couldn't find a way to ...

Ways to prevent my website from being accessed through the Uc Browser

Is there a way to prevent my website from functioning on UC Browser using HTML or JavaScript? ...

Synchronizing data between two Vue components when deleting an item

Feeling uncertain about the approach I am taking with this data. Essentially, I have the following dataset: surrounding: { data: [ { id: 1, name: 'test' }, { id: 2, name: 'test' }, { id: 3, name: 'test& ...