Creating flexible Vue routes using a single router component and a navigational menu

I am working on a Vue project and I want to implement nested routes in my router.js. My goal is to have just one menu for all the nested routes and only one

<router-view></router-view>
in a master component.

This is what I envision (in pseudocode):

<master>

  <menu>
  </menu>

  <router-view>    
  </router-view>

</master>

In my router.js, I have:

{ 
  path: '/master',
  name: 'master',
  component: Master,
  children:[
    {
      path: ':team',
      name: 'team',
      component: Team,
      children:[
        {
          path: ':group',
          name: 'group',
          component: Group,
          children:[
            {path: ':one',
            name: 'one',
            component: One}
          ]
        }
      ]
    }
  ]
}

Within my Master.vue file, I have:

<template>
  <div>

        <router-link class="link" :to="{name:'team', params: {team: 'ta'}}">team a</router-link> 
        <router-link class="link" :to="{name:'team', params: {team: 'tb'}}">team b</router-link> 
        <router-link class="link" :to="{name:'group', params: {group: 'ga'}}">group a</router-link> 
        <router-link class="link" :to="{name:'group', params: {group: 'gb'}}">group b</router-link> 
        <router-link class="link" :to="{name:'one', params: {one: 'oa'}}">one a</router-link>  
        <router-link class="link" :to="{name:'one', params: {one: 'ob'}}">one b</router-link>    

      <router-view></router-view>
  </div>
</template>

<script>   
    export default {
        name: "Master"
    }
</script>  

Unfortunately, this setup is not functioning as expected. When I navigate from team b to a group, the URL becomes ta/ga instead of tb/ga.

Additionally, I am receiving these warnings:

[vue-router] Duplicate named routes definition: { name: "team", path: "/master/:team" }
[vue-router] Duplicate named routes definition: { name: "group", path: "/master/:team/:group" }
[vue-router] Duplicate named routes definition: { name: "one", path: "/master/:team/:group/:one" }
[vue-router] Duplicate named routes definition: { name: "master", path: "/master" }
[vue-router] missing param for named route "group": Expected "team" to be defined
[vue-router] missing param for named route "one": Expected "team" to be defined

I could simplify by removing nested routes and using path: ':team/:group/:one' but I'm unsure if that's the correct approach or aesthetically pleasing.

Is there a way to achieve both nested routes and a single menu/router structure? I appreciate any guidance you can provide.

Thank you.

Answer №1

When dealing with groups, it's important to include team parameters. For example, if you click on TEAM B, you would send the parameter TB. Then, if you click on GROUP A, you would only send the parameter GA, effectively discarding any previous information related to 'TB'.

To address this issue, you can utilize $route.params.id within a nested router link that is only visible when a team is selected. Here's an example:

<router-link class="link" :to="{name:'group', params: {group: 'ga', team: $route.params.team}}">group a</router-link>
<router-link class="link" :to="{name:'group', params: {group: 'gb', $route.params.team}}">group b</router-link>

You can also enhance your code by activating the group links only when the user selects a team first (forcing them to choose a team before selecting a group).

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

Is it possible to enable a button as soon as input is entered?

I'm encountering a minor issue with my button's functionality. I am attempting to have the button enabled as soon as text input is entered into the text field, but currently it only becomes enabled after the focus has changed from the text field. ...

A guide on dynamically showcasing/summoning icons in react by utilizing array data

QUESTION: 1 (SOLVED!) https://i.stack.imgur.com/1M1K7.png What is the best way to display icons based on an array of data codes? const data = [{ img: '01d' }, { img: '02d' }] if(data) { data.map((item) => ( <img src={`./ ...

Error 404: "Headers already sent to the client cannot be modified"

I'm currently developing a Node/Express application and I want it to display a 404 page if a promise function doesn't resolve. This is my approach: app.get("/projects", t("projects", function(req, res) { res.header("Cache-Control", "private ...

Displaying Name Values in a <v-select> Component and Passing the Corresponding ID in the Axios POST Request in Vue.js

UPDATE: Issue resolved by including the return-object prop in v-select When a new student is added to the database using a vuetify form, I want to be able to assign them a course that exists within a list of available courses (also stored in the database) ...

I am a newcomer to Stack Overflow and I am facing difficulty in getting my form to submit successfully

Excuse any errors as I am new to this. I am facing an issue where my form is not submitting anything in the console. Could it be because my entire HTML file is within a return statement from a JavaScript function? I assumed it would work since I imported a ...

The sort function in Reactjs does not trigger a re-render of the cards

After fetching data from a random profile API, I am trying to implement a feature where I can sort my profile cards by either age or last name with just a click of a button. Although I managed to get a sorted array displayed in the console log using the h ...

Struggling with xml2js within the Quasar framework version 2.6.0

To integrate the following code into a Quasar 2.6.0 application, I am encountering an issue that needs attention. async fetchAbstracts() { try { const url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=33888705,183 ...

Steps for integrating Stanford's NLP into a web application

I have successfully developed a project utilizing Stanford's NLP API and models. Now, I am looking to integrate this Java-based project onto the web. After seeing the demo provided by Stanford-NLP, I am curious about the process they use to achieve th ...

When trying to manually trigger the firing of the autocomplete function to get a place using Google API

My goal is to retrieve the data from autocomplete.getPlace() when triggering this event manually. Essentially, I have a function that captures the user's location in Lat/Lng format, and afterward, I aim to access other useful data using getPlace() su ...

Select component with nested checkboxes for multilevel dropdown

I am interested in developing nested dropdowns with checkboxes, similar to the example shown in this image: Image 1 Is there a way to achieve this functionality using React? I have not been able to find any specific library that allows for this implement ...

What steps can I take to stop a browser from triggering a ContextMenu event when a user performs a prolonged touch

While touch events are supported by browsers and may trigger mouse events, in certain industrial settings, it is preferred to handle all touch events as click events. Is there a way to globally disable context menu events generated by the browser? Alternat ...

Tips for displaying JSON data in HTML without the use of placeholder DIV elements

Customer Scenario: A user wants to search through Wikipedia. The search results should be limited to 5 articles, and the user should be able to view the title and introduction of each article. Developer Scenario: User input is provided via an HTML input f ...

Do JavaScript Promises operate asynchronously?

Can we clarify if JavaScript Promise is asynchronous? I've been researching Promise and async programming, particularly with ajax requests. If Promise isn't inherently async, how can we make it so? For instance, consider a function that encapsul ...

I'm not satisfied with the value of the ReactJs state after the change

I am working on creating a calendar app for practice purposes. Currently, I have a current_month state variable set to 1. Additionally, I have a function called IncreaseMonth() that is designed to increment the value of current_month. However, when the va ...

One question I have is how I can successfully send a value within the RxJS subscribe function

I am currently in the process of transitioning the code to rxjs Here is my original code snippet. userAuth$: BehaviorSubject<ArticleInfoRes>; async loadArticleList(articleId: number) { try { const data = await this.articleApi.loadArticl ...

Packages starting with @ are found in the Node.js ecosystem

What's the deal with libraries in Node.js starting with @ symbols? Is there a specific convention for this? I feel like I'm missing something obvious here. ...

What is the most effective method for sorting through vast amounts of data with Javascript, React, and Redux?

Currently, I am working with a minimum JSON data set of 90k [...] and utilizing the .filter method. Everything is functioning correctly without any issues, however, from a performance standpoint, I am curious about potential improvements. Any suggestions o ...

Setting up a retrieval callback in mongoose and storing it in a global variable

Is there a way to set the value of db as a global variable? I am having trouble with getting the console output of name outside of the findOne function, it keeps showing me undefined. Any suggestions on how to fix this issue? var name; schema.findone({na ...

Why isn't my onClick event functioning as expected?

I used the handleClick function in an onClick event, but it's showing an error (this is not defined). var Buttons = React.createClass({ getInitialState() { return { field: ':P ' } }, handleClick(field ...

Please use Shift + Enter feature only when using desktop devices

In my React chat application, I have implemented a textarea for message input to allow multiline support. This works smoothly on mobile devices as pressing Enter creates a new line and a send button is available to submit the message. However, I want a di ...