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

Managing state in React for a nested object while still maintaining the data type of the

Exploring the question further from this particular query Updating State in React for Nested Objects The process of updating nested state involves breaking down the object and reconstructing it as shown below: this.setState({ someProperty: { ...this.stat ...

Tips for ensuring an element is visible in CUCUMBER JS?

Whenever I run my code, it keeps returning the error message: NoSuchElementError: no such element: Unable to locate element Even though I have set up a wait function, it does not seem to actually wait. The step fails immediately without waiting for the s ...

Unleashing the Power of Aurelia's HTML Attribute Binding

I need to bind the "required" html attribute in my template and model. Along with passing other information like the label value using label.bind="fieldLabel", I also want to pass whether the element is required or not. However, simply using required="tr ...

Is there a way to establish communication between two ReactJS components by utilizing Jotai?

I am facing a problem with 2 reactjs files: Reports.js (handles report requests and displays results) AuthContext.js (maintains communication with backend server through a socket connection) The user initially visits the report page generated by Reports. ...

Prevent the SnackBar from extending to full width in case of a smaller window size

Is there a solution to prevent the SnackBar from spanning the entire width of the screen when the window is narrow? ...

Disable the ability to select all checkboxes in the Quasar Table component

Currently working with Quasar and I have implemented a table with multiple selections just like the image below: I am facing an issue where I cannot figure out how to hide the checkbox in the header that selects all options in the table. Here is the code ...

A step-by-step guide on transferring Data URI from canvas to Google Sheet using the fetch method

I am trying to send an image as base64 code to a Google sheet using fetch. However, I am encountering an error that says "data_sent is not defined" when I run my code. I need help identifying the problem and finding a solution to fix it. For reference, & ...

What is the best way to verify the invocation of a Vuex Mutation within a Vue component?

Imagine you have a Vue component with a method structured like this: methods:{ doSomething(someParameter){ //potentially manipulate the parameter in some way this.$store.commit("storeSomething",someParameter); let someP ...

Show a variety of logos on the website based on the current date

I've been experimenting with displaying a unique logo on my website based on the current date (for example, showing a Christmas-themed logo during December). Here's what I have so far: <img class="logo" id="global_logo" sty ...

Sending a JSON Object to an API endpoint using the $.ajax method

While attempting to extract data from a form by clicking a button and sending it to a web method in my code behind, I am aiming to pass it as a JSON object, following what seems to be the convention. Below is the current code snippet that I have, but unfor ...

A Node.js feature that enables atomic file replacement, triggering watchers only once

I have a unique scenario where I need to handle two types of processes. One process is responsible for writing a file, while the other processes are required to read it whenever there is a change. In my research, I came across fs.watch as a solution to ke ...

How do I save the value of a callback function in Vue data?

#I am facing an issue where the value of this.zuobiao is not being logged after I call the function that assigns a value to it. Why is this happening? getUserProfile() { uni.getLocation({ type: 'gcj02 ', geocode: true, success: (res) => ...

What is the best way to handle responses in axios when dealing with APIs that stream data using Server-Sent Events (S

Environment: web browser, javascript. I am looking to utilize the post method to interact with a Server-Send Events (SSE) API such as: curl https://api.openai.com/v1/completions \ -H "Content-Type: application/json" \ -H ...

Organizing a series of objects into groups of four for processing

I have a task of organizing an array of objects that represent game players by assigning each player to a group number based on their current group value. The challenge is to ensure that each group has as close to four players as possible, while also acco ...

Generate a new array using a single value extracted from an existing array

I'm new to working with arrays. Before this, I used to manually code everything in HTML. My question is, can you create an array based on the values of another array? var pmmain =["aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", ...

Create a custom Angular directive that allows you to replace tags while inserting the template

I have created a custom directive that can take templates based on the attribute provided. Check out the Plnkr example JS var app = angular.module('app', []); app.directive('sample', function($compile){ var template1 = '<d ...

Having trouble with Material-UI Textfield losing focus after re-rendering? Need a solution?

I am currently utilizing Material-ui Textfield to display a repeatable array object: const [sections, setSections] = useState([ { Title: "Introduction", Text: "" }, { Title: "Relationship", ...

Launch a dialogue box by clicking on the buttons corresponding to the article ID

I am currently in the process of setting up an admin panel with some quick actions for managing my articles, such as deleting them. When I click on the trash can icon, a dialog box should open and prompt me to confirm the deletion. This dialog box should b ...

Is your Laravel and vue js "add to cart" button malfunctioning?

Hey there! I'm currently working on an e-commerce project using Laravel and Vue. I have successfully managed to add products to the cart, but I'm facing an issue where the quantity in the cart remains at 0 until I refresh the page. I've trie ...

Discover the method to retrieve HTML content by sending an HTTP POST request in AngularJS, similar to loading content

My attempt to retrieve HTML content using Angular Js Post HTTP method was successful, but only for text contents like P tags. I am now trying to fetch HTML contents that include input types such as text boxes using Angular JS. Interestingly, when I utilize ...