vue-router default route for children

Currently, I am working on a Vue 2.x application and utilizing vue-router for routing purposes.

In certain situations, I need to directly display a child vue. The template structure is as follows:

| voice 1 | voice 2 | voice 3 |

    | submenu 1 | submenu 2 | submenu 3 |

|
| content 1
|

The concept is simple - upon selecting a menu voice, the corresponding submenu is shown; similarly, selecting a submenu voice displays the associated content.

The routing system mirrors the menu structure so that if you navigate to /voice1/submenu1, it should display content 1. By clicking on submenu2, you are directed to /voice1/submenu2 to show content 2, and so forth.

Upon user login, rather than presenting an empty page, I prefer having default components preloaded in the route (such as voice 1, submenu 1, content 1). However, I am uncertain about the optimal approach. Currently, I have addressed this by adding the following snippet in my route interceptor:

router.beforeEach((to, from, next) ⇒ {
  const token = store.getToken();

  const tokenIsValid = validateToken(token);
  const routeDoesntNeedAuth = routeWithoutAuth.indexOf(to.fullPath) > -1;

  if (tokenIsValid || routeDoesntNeedAuth) {
    if (to.fullPath === '/') {
      next('/voice1/submenu1');       // <- this line does the trick
    }

    next();
  } else {
    next('/login');
  }
});

While this solves the immediate issue, I believe there could be a more efficient way to achieve the desired outcome. Here is how my route system is structured:

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      component: AppWrapper,
      children: [
        {
          path: '/voice1',
          components: {
            default: PageWrapper,
            subMenu: VoiceFirstSubMenu,
          },
          children: [
            {
              path: 'submenu1',
              components: {
                mainContent: ContentOne,
              },
            },
            {
              path: 'submenu2',
              components: {
                mainContent: ContentTwo,
              },
            },
            {
              path: 'submenu3',
              components: {
                mainContent: ContentThree,
              },
            },
          ],
        },
      ],
    },
    {
      path: '/login',
      component: Login,
    },
  ],
});

If anyone has insights on enhancing this process, please share your thoughts!

Recently, Divine raised a crucial question which pointed out that a specific line of code was causing redirection of all routes to /:

this.$router.push('/');

This misstep was within a wrapper component containing the entire application. Once I removed that line, everything functioned flawlessly.

Answer №1

To implement a redirect in the route configuration, you can utilize the redirect property.

For instance, if the / route is accessed, Vue.js will automatically navigate to /voice1/submenu1.

routes: [
    {
      path: '/',
      redirect: '/voice1/submenu1', <---- The / route will be redirected to /voice1/submenu1
      component: AppWrapper,
      children: [
         ...
      ]
    },
]

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

How to stop parent event propagation in jQuery

I am facing a frustrating issue with my code. Every time I toggle a checkbox, the parent element's click event also triggers. I have experimented with various solutions like: event.stopImmediatePropagation(); event.stopPropagation(); event.preventD ...

JS/JQuery: Retrieve value from dropdown list or input field

I'm looking for a way for my user to choose a value from a drop-down menu, but if they can't find the right option there, I want them to be able to input a custom value. I've figured out a workaround by deactivating the drop-down and activa ...

Invoke Office script from beyond MS Excel WebApp

Within the Excel WebApp on Office 365, users have the ability to incorporate Office Scripts through the "Automate" tab. These scripts utilize JavaScript syntax and can automate Excel functions similar to a VBA macro, specifically designed for the Excel Web ...

The Countdown Timer in React Native triggers an error due to Invariant Violation

According to some expert advice from this stackoverflow answer, I attempted to implement a countdown timer for my project as shown below. constructor(props: Object) { super(props); this.state ={ timer: 3,hideTimer:false} } componentDidMount(){ this. ...

Is it possible to create a pie chart using Chart.js with data fetched through an Ajax HTTP GET

Embarking on a new journey here, this week's focus is on delving into Chartjs for canvas and brushing up on JSON usage. The task at hand includes employing an Ajax HTTP GET request to fetch the json file. However, I am currently stumped on how to trig ...

Trouble With Ajax Submission in CakePhp: Issue with Form Serialization

In my attempt to utilize ajax for sending an array of objects along with serialized form data, I encountered a problem. The issue arises when I include the array in the ajax data along with the serialized form data. This results in the serialized form data ...

Learn how to trigger the keydown function in VUE programming

I am trying to create a method that will be triggered whenever any key on the keyboard is pressed, regardless of where the focus is. I want to be able to determine which key was pressed in this method. Currently, I have set up an event listener for keydow ...

Regular expression for matching zero's following a decimal

I'm currently working on a regex method to validate decimals that only allow 2 numbers after the decimal point. For example, it should return true for 1.00 and false for 1.000, which it currently does. However, I also want it to return false for value ...

Update the formatting of the dates in the dateRangePicker

Utilizing a dateRangePicker, I am receiving dates in the format "mm-dd-yyyy". Below is my HTML code: <input type="text" name="TextDate" value="10/24/1984" /> Here is the script being used: <script> $(function() { $(&apos ...

React Weather App experiencing issues with prop communication and updating variables

My innovative weather app allows users to input custom longitude and latitude coordinates. Once the coordinates are received, they are passed as props to a child component where they are used in an API call to fetch data for that specific area. While ever ...

Ways to address issues in my tree-building algorithm when the parent ID is missing

Currently, I'm in the process of creating a function to build a tree. Everything seems to be functioning correctly until I encounter a scenario where a document is added with a parentID that doesn't exist in the list. The root node is intended to ...

What is the proper way to access an element from the state within a foreach loop in Vuex?

Currently in my Vue application, I'm utilizing Vuex. Within the store, there is an object declared like so: state: { list: { a: false, b: false, c: false } } In the mutations section, there ...

Facing challenges in both client-side and server-side components

import axios from 'axios'; import Image from 'next/image'; export const fetchMetadata = async({params}) => { try { const result = await axios(api url); return { title: title, description: Description, } / } catch (error) { con ...

Tips to stop automatic scrolling when tapping on a tab

Currently, I am encountering an issue with the tabs in my project. Whenever I click on a tab, the page scrolls down and I can't seem to figure out why. Below is the snippet of my HTML code: <ul class="list"> <li class="tab1 active"> ...

Exploring the Differences in CSS Styling between Web and Mobile Platforms

Recently, I launched my new website and encountered a peculiar issue. Upon clicking on Pickup Date & Time, a bootstrap datepicker pops up like it should. However, the problem arises when viewing the website on mobile devices - the datepicker appears offsc ...

Ways to assign the value of an alert to an element

Within this piece of code, my intention is to retrieve the alert value and apply it to an element. Description: The AJAX code I have written checks for values in a database, fetches new values from the database, and then displays these fetched values in a ...

JavaScript event listener for SVG path element click is not functioning correctly as anticipated

How to determine if an element or its children have been clicked? I am trying to identify when a parent element or any of its child SVG icons with the attribute name set to "setGameState" have been clicked. The issue I am facing is that sometimes the even ...

What is the best way to combine API calls using rxJs subscribe and map in Angular?

Currently, I am executing multiple API requests. The first one is responsible for creating a User, while the second handles Team creation. Upon creating a User, an essential piece of information called UserId is returned, which is crucial for the Team cre ...

Enhancing Next.js SEO with 'use client' Metadata

Currently, I am facing an issue with my product page. The metadata for this page is fetched from the backend using an API that retrieves data from a database. To fetch this data and update it on the client side, I am utilizing a custom hook. However, the p ...

Using Regular Expressions in Firebase Functions to achieve a 'Clean Path' when utilizing app.use() in Express.js

Objective: I want Express to return /register when the browser URL is http://localhost:5000/register. This seemingly simple goal is proving to be a challenge with Express. Let's start by looking at my firebase.json: firebase.json: "hosting": { ...