Nested routes are arranged in the depths and a variety of components appear depending on the path of the

I've encountered a situation where I have deeply nested routes in my routes.js file. The code snippet below shows that depending on the route, I need to render different components. For instance, if the route is for products, I should render the Products.vue component. However, if the route goes deeper, I need to render the EmptyRouterView.vue component which contains the template

<router-view></router-view>
to enable rendering of sub route components.

{
    path: '/products',
    name: 'products',
    component: {
        render(c) {
            if (this.$route.name === 'products') {
                return c(require('pages/Products/Products.vue').default)
            } else {
                return c(require('components/EmptyRouterView.vue').default);
            }
        }
    },
    meta: {
        requiresAuth: true,
        allowedPositions: '*'
    },
    children: [
        // Scan product to get info
        {
            path: '/products/search-product',
            name: 'search-product',
            component: () => import('pages/Products/SearchProduct.vue'),
            meta: {
                requiresAuth: true,
                allowedPositions:   '*'
            }
        },
        ....
    ]
}

I'm curious if there's a more concise or efficient way to achieve this. Perhaps something along these lines (even though I understand that using `this` in an arrow function is not valid):

component: () => {
    this.$route.name === 'products' ? require('pages/Products/Products.vue').default : require('components/EmptyRouterView.vue').default
}

Alternatively, do you think there might be another approach altogether to handle this scenario?

If you require any further information, feel free to ask and I'll provide it. Thank you!

Answer №1

One approach is to create a separate file with a .vue extension and include both components inside it (<cmp-1 /> & <cmp2 />). Then, within the template, you can set up an if-statement using another template tag:

<template v-if="conditional">
<cmp-1 />
</template>
<template v-else>
<cmp-2 />
</template>

The condition for the if statement can be based on your route.

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

Using optional chaining on the left side in JavaScript is a convenient feature

Can the optional chaining operator be used on the left side of an assignment (=) in JavaScript? const building = {} building?.floor?.apartment?.number = 3; // Is this functionality supported? ...

Using JavaScript to toggle the iron-collapse property

I've implemented multiple <iron-collapse> elements with unique IDs, each one corresponding to a <paper-icon-button>. On screens wider than 650px, I can interact with the <iron-collapse>s using their respective buttons. But on narrow ...

Preserving Previous Values in Vuetify Select

Experience a unique way of handling Vueitfy selections with this code snippet: <v-select label="..." autocomplete append-icon="search" :items="plots" item-value="id" item-text="plotHeader" v-model="selectedPlot" v-on:change="loadPlotInforma ...

Modify one specific variable within my comprehensive collection on Firebase Firestore

After clicking the button, I need to update a variable. The variable in question is "bagAmount" and it is stored in my firestore collection. Here is a link to view the Firestore Collection: Firestore Collection Currently, I am able to update one of the va ...

Twitter API causing issues with setTimeout function in Node.js

Attempting to read from a file and tweet the contents in 140 character chunks, one after the other has proven to be quite challenging. Despite verifying that other parts of the code are functioning correctly, using a simple for-loop resulted in tweets bein ...

Steps for choosing an option in MUI select list using jest

I am looking for a way to automate tests for a Material UI select component using Jest. Is there a way to select an option from the list of options in the Material UI component and confirm that its value has been successfully populated in Jest? I have se ...

VueJS does not support certain characters in its JavaScript replace function

In my current situation, I am utilizing the replace method in the following manner: <code v-html="'/<try>/'.replace(/(?:\r\n|\r|\n)/g, 'testing')"></code> As I work with a longer string t ...

Universal Module Identifier

I'm trying to figure out how to add a namespace declaration to my JavaScript bundle. My typescript class is located in myclass.ts export class MyClass{ ... } I am using this class in other files as well export {MyClass} from "myclass" ... let a: M ...

Utilize Axios to send data in real-time to update any changes made to an input field in

Just wanted to write about this topic because I have a burning question. (Please note that the code in this post is just an example). I'm struggling with sending the input content of name_contact on each change without using a button. Is it even poss ...

Implementing a sleek show/hide transition using slideToggle in jQuery

Trying to implement show/hide content with slideToggle and it's functioning, but the animation effect on the table is not smooth. Attempted two different codes, but none provided the desired animation effect: $('.more').slideToggle(' ...

Out-of-sync movement in animated characters

Looking for some assistance with my page coding. I have a scenario where two stars are moving around a button, simulating an animation by incrementing the CSS properties top and left. Initially, everything appears fine and they move synchronously. However, ...

What could be the reason for the malfunction of jQuery's show() function?

Using jQuery, I have implemented a functionality to hide a div using the hide() method. However, upon clicking a link, the div is supposed to show but unexpectedly disappears after appearing briefly. HTML Code Snippet <div id="introContent"> & ...

Tips for Displaying and Concealing Tables Using Radio Buttons

Does anyone know how to refactor the jQuery code to toggle between two selection options (Yes and No)? This is the jQuery code I have tried: $(document).ready(function() { $("#send_to_one").hide(); $("input:radio[name='decision']").chan ...

Exploring the Magic of ES6 Object Destructuring

Learning about ES6 destructuring is still new to me. I have encountered a scenario where I need to extract specific values from a nested object within an object. For instance - z = {g: 1, h: 2, i: {d1:5, d2:6, d3:7}} When attempting to destructure with ...

ajax memory leakage

Encountering a gradual memory leak issue in Internet Explorer and Firefox while utilizing a mix of ASP.NET AJAX and jQuery. The situation mirrors the one portrayed on this post: Preventing AJAX memory leaks, but with jQuery and ASP.NET AJAX instead of prot ...

Address NPM vulnerabilities through manual fixes

I downloaded a repository and ran an npm install, but encountered an error at the end. Now, every time I run npm audit, I receive the following message: found 18 vulnerabilities (5 low, 12 moderate, 1 high) in 15548 scanned packages 9 vulnerabilities requ ...

What is the best way to dynamically insert an email value into a JSON file?

Here is the structure of my JSON file: test.json: { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3b8a1baa093beb2babfbabdb2a7bca1fdb0bcbe">[email protected]</a>", "password": "Sanju@143", ...

React: Submit button not triggering form submission despite having a valid submit event handler and correct syntax

My question stands out from existing ones as it features valid syntax, correct use of type="submit" on the button, and a simple onSubmit handler on the form. Despite this, clicking the button fails to trigger the onSubmit handler. To illustrate ...

Crack open a JSON object

I am struggling to parse a JSON object. It seems like the code is not working, can you help me? var mock_data = { "available": [{ "UserID": 7, "UserName": "Manoj", "Language": "Java", "Score": 9, "TimeLimit": 4.0 }, { "UserID ...

Is there a way to assign a dynamic value to an input just once, and then retain the updated value without it changing again

During a for loop, I have an input element (type number) that needs its value modified by decrease and increase buttons: <div class="s-featured-list__item s-featured-list__item--expandable" v-for="(item, itemIndex) in category.items" ...