creating intricate nested routes within the same Vue component by using a conditional switch case

I am currently developing a players module. Within this module, there are 3 routing cards on the initial page. Each card leads to the next page, which contains multiple routing cards related to their parent card.

For Example:

  1.  1st level Card(Player Name) --> 2nd level Cards(Players Info, Player Statistics, Records) --> up to 3rd level routing

  2.  1st level Card(Grounds) --> 2nd level Cards(Grounds Info, Match played, Records) --> up to 3rd level routing

  3.  1st level Card(Match Information) --> 2nd level Cards(Match info, match history, community resources) --> up to 3rd level routing

Now, I have created components with respective routes for all these. However, I want to create one component to handle routing based on conditions ($route.path).

Below is my routes.js file:

{
    name: 'Players',
    path: '/players',
    component: PageLayout,
    meta: {
        topNavigation: true
    },
    redirect: { path: '/players/entry' },
    children: [
        {
            name: 'PlayersEntryPage',
            path: 'entry',
            component: PlayersEntryPage
        },
        {
            name: 'PlayersName',
            path: 'name',
            component: PlayersName
        },
        {
            name: 'Grounds',
            path: 'grounds',
            component: Grounds
        },
        {
            name: 'MatchInformation',
            path: 'info',
            component: MatchInformation

        }
    ]
}

This is the homepage and the 1st level subsequent card components for routing:

PlayersEntryPage

<template>
    <vu-page background="gray">
        <vu-container>
            <vu-row-control class="mt-3">
                 <vu-box-control :list="cardLists" @click="cardAction"></vu-box-control>
            </vu-row-control>
        </vu-container>
    </vu-page>
</template>

<script>
export default {
    data() {
        return {
            cardLists: [
                { heading: ‘PlName', content:’Players Name and information',to:'/players/name'},
                { heading: ‘Grnd',  content:  ‘Ground Information', to:'/players/grounds' },
                { heading: ‘Infos', content:  ‘Match Informations', to:'/players/info' }
            ]
        };
    },
    methods: {
        cardAction(value) {
            if(value) {
                this.$router.push(value.to);
            }
        }
    }
};
</script>

1st level component (PlayersName) -> 2nd level component cards

<template>
    <vu-page background="gray">
        <vu-container>
            <vu-row-control class="mt-3">
                 <vu-box-control :list="cardLists" @click="cardAction"></vu-box-control>
            </vu-row-control>
        </vu-container>
    </vu-page>
</template>

<script>
export default {
    data() {
        return {
            cardLists: [
                { heading: ‘Players Personal Info', to:’/players/name/pinfo'},
                { heading: ‘Players Statistics', to:'/players/name/statistics' },
                { heading: ‘Players Records',to:’/players/name/records' }
            ]
        };
    },
    methods: {
        cardAction(value) {
            if(value) {
                this.$router.push(value.to);
            }
        }
    }
};
</script>

Box-control code snippet

<template>
    <div class="box-wrapper">
        <div v-for="(items, i) in boxes" :key="'box-row-' + i" class="box-container">
            <vu-button-control
                v-for="item in items"
                :key="item.heading"
                plain
                class="box"
                :to="item.to"
                @click="click($event, item)"
            >
                <vu-row-control>
                    <vu-column-control cols="10">
                        <h1 class="label">{{ item.heading }}</h1>
                        <p class="body_content">{{ item.content }}</p>
                    </vu-column-control>

                    <vu-column-control cols="2">
                        <vu-button-control @click.stop=“addFavouriteClick(item)”>
                        </vu-button-control>
                    </vu-column-control>
                </vu-row-control>
            </vu-button-control>
        </div>
    </div>
</template>

All other routing cards follow the same structure, with only differences in the passed data. This is why I want a single component that can handle different routes based on the $route path.

I am considering using a switch case approach but struggling with the conditional routing part.

Answer №1

Apologies if I may have misunderstood your issue, but based on my understanding, here is a possible solution:

  • You seem to have three levels of routing
  • Each route has its own component
  • You are interested in consolidating all routes into a single handling component

To achieve this, the approach would involve extending the router to pass subroutes props to a general component:

const PlayersInfo = {
  template: `
    <div>Players info component</div>
  `
}

// Other components defined as per requirements...

const CommunityResources = {
  template: `
    <div>Community resources component</div>
  `
}

// RoutingControl component implementation...

// Routes and subroutes configuration...

// Function to automatically retrieve subroutes for router setup

// "Fixing" the routes array scope...
.link {
  padding: 0 8px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <router-view />
</div>

I hope this provides some insight into what you were hoping to achieve :)

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 there a way to control the quantity of items being displayed in my ng-repeat directive?

Here are the objects in my array: 01-543BY: Array[1] 03-45BD23: Array[1] 03-67BS50: Array[1] 06-78FR90: Array[1] 07-467BY3: Array[1] 09-23DF76: Array[1] Currently, I have a total of six objects, but I only want to display four. This is how I am using ng- ...

Uploading images simultaneously while filling out a form

Currently, I have a form that requires users to fill it out and upload an image. However, there is a delay of up to 30 seconds when the user hits "Submit" due to the image size being uploaded. I'm interested in finding a way to initiate the image upl ...

What is the best way to integrate a button within a datatable cell to display additional details in a popup window?

I am seeking help with datatable.js. I would like to insert a button inside the cells of the datatable columns to expand and display the detailed content of each cell. When I click on the red button, a popup modal should appear showing the full list of con ...

Stop the entire page from scrolling when scrolling within a specific div element

I am looking for a solution to prevent the page from scrolling back to the previous section while scrolling within a specific div element. Currently, I am using Alvarotrigo's fullpage scroll plugin, although I am not sure if that is relevant to the is ...

Steps for uploading an item to an API using an Excel document

I'm facing an issue where I am trying to send a large object along with an Excel file to an API. However, only my photo is being recognized and the object is not sent, resulting in an [object Object] error. I understand that this error occurs due to i ...

Error message: JavaScript is unable to save data to an array retrieved from Ajax, resulting in

I am facing an issue with retrieving continuous data from the database using AJAX and storing it in a JavaScript variable. Despite my efforts, I am unable to populate an array with the retrieved values as they always end up being undefined. Below are the s ...

Using JavaScript to make an AJAX call to a different domain while bypassing the Content Security Policy restrictions

While parsing a web page, I need to initiate an AJAX call to my localhost depending on the content. The purpose is to exchange data using a PHP script on my localhost, possibly in JSON format (still under testing). This process is part of a plugin that I ...

Exploring the capabilities of Vue JS to dynamically update data and model bindings within form

I need help creating a form that allows users to edit their comments. The challenge is to display the current value of the comment using dynamic data from v-for, while also binding the value to a model for sending it with a patch request. Here is an examp ...

Sending the selected option from a dropdown menu to populate a textbox on a separate webpage using PHP, jQuery, and AJAX

I am looking to dynamically update the value of a dropdown in index.php to a textbox in test.php using Ajax. The scenario involves having test.php embedded as an iframe within index.php. Upon changing the dropdown selection, the corresponding value should ...

Node application experiencing issues retrieving SVG files during production

When testing my application locally, the svg files display correctly with the code below (Angular.js variables are used within curly brackets): <img ng-src="img/servant_{{servant.personality}}.svg" draggable="false"> However, once deployed on Herok ...

Error: Google chart for Google Maps is not displaying text every 1 unit as expected

I am looking to display all the hAxis labels in my chart. Due to the extensive length of the code exceeding 4000 lines, I will only include what I consider to be crucial: var data = new google.visualization.DataTable(); data.addColumn('string', & ...

The Jquery .change() function refreshes the results just once

I am working on a form with 3 input fields named #first, #second, and #third, along with a fourth field labeled as #theResult. <div id="addFields"> <span id="addFieldsHeader">Add The Fields</span> <table style="margin:0 auto;"> ...

dynamically display elements within aframe based on specific conditions

In my aframe scene, there are three icosahedrons, a complex particle system, and a cursor that fuses on objects within the scene. The performance of the scene is affected when the particles are visible because the cursor attempts to fuse with every particl ...

Implementing raw static HTML files in webpack: a step-by-step guide

Recently, I created a basic template called test.html <div>raw text with content</div> All I'm trying to achieve is to import the raw file without any alterations For example: require('./test.html'); // This should return "&l ...

Ways to provide information to an rxjs observer

It appears that most people find observers to be a piece of cake, but I personally struggle with them. I am trying to set up an observable that can receive a number input after it has been created, triggered by pressing a button. However, all the examples ...

Passing a value back to a template from a promise

Currently, I am implementing server-side validation for dynamically created input fields within div tags. The issue I am facing is that I need to display the API error message in my template instead of directly setting it in my controller. If I set it in t ...

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

When using @testing-library/react (rtl), the 'waitFor' function achieves success even without the need for the 'await' keyword

waitFor() is causing my test to fail while waitFor() (without await) makes it pass. The official documentation states: Async methods return a Promise, so you must always use await or .then(done) when calling them. (https://testing-library.com/docs/guide ...

``When executing the `npm install` command, it does not install the sub-dependencies of a local package

I am facing an issue with my packages. One package named package-a has a dependency on another package called package-b which is not published on npm but resides in my file system. When I try to run npm install from the directory of package-a, the dependen ...

Ways to display the values of angular variables within ng-bind-html

Converting HTML content from a database saved as varchar to front end JavaScript code can be tricky. The content is stored in a variable called vm.htmlContent and must be displayed as HTML on a web page. To achieve this, the ng-bind-html angular directive ...