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

Angular5 causing all divs to have click events at once instead of individually triggered

I am a beginner when it comes to working with Angular and I have encountered an issue. I created a click event on a FAQ page in Angular 5, but the problem is that when I click on one FAQ, they all open up instead of just the targeted one. Here is my TypeS ...

Issues arise with the functionality of CSS and JavaScript after successfully deploying a Next.js and React project to the server side

I need to deploy my React+Next and Node.js projects on the same port. To achieve this, I converted my TypeScript files to JavaScript and moved the .next folder to the backend side. Now, my API and frontend code are functioning on the same port thanks to Ex ...

Step-by-step guide on transferring an HTML5 sqlite result set to a server using AJAX

Imagine I have a scenario where I receive a result set as shown below: db.transaction( function(transaction) { transaction.executeSql( 'SELECT col1, col2, col3 FROM table;', [],function(transaction, result){ //need to find a ...

Experiencing occasional "Cannot GET /" error when using node.js on Bluemix

My Bluemix services are giving me trouble. I keep encountering the error "Cannot GET /pathname" on my node.js express services. Strangely, this issue only occurs about one-third of the time. There is no logging or error messages in the application when thi ...

Troubleshooting issues with JSON compatibility within the OnChange event

Initially, I wrote this code to retrieve a single data point. However, I realized that I needed more fields returned when the drop-down select menu triggered an onchange event. So, I switched to using JSON, but now it's not returning any data. The dro ...

The AMP HTML file is unable to load due to the robots.txt file on https://cdn.ampproject.org restricting access

I've been trying to fetch and render my AMP HTML files individually, but they all seem to be encountering the same issue. According to the Search Console report, it says "Googlebot was unable to access all resources for this page. Here's a list: ...

Whenever I try to relocate my HTML file that references three.js, the three.js library seems to malfunction and stop

Something strange is happening... I recently downloaded three.js into a directory named 'brick': git clone https://github.com/mrdoob/three.js.git which created a subdirectory: brick/three.js/ After navigating to brick/three.js/examples ...

What is the purpose of including an es directory in certain npm packages?

Why do developers sometimes have duplicated code in an es folder within libraries? Here are a few examples: https://i.stack.imgur.com/BWF6H.png https://i.stack.imgur.com/3giNC.png ...

Setting up Socket.io results in numerous transport polling GET requests being initiated

I have set up an express.js server-side and followed the socket.io guide. However, I am facing issues with the socket connection not being successful, and there seems to be a high number of unexpected GET requests like this: https://i.stack.imgur.com/GDGg ...

Steps to create a zigzagging line connecting two elements

Is it possible to create a wavy line connecting two elements in HTML while making them appear connected because of the line? I want it to look something like this: Take a look at the image here The HTML elements will be structured as follows: <style&g ...

Is there a way to change a model attribute in JSP based on the AJAX response?

I have a JSP page that contains the following code snippet: <li id="notifications"> <c:choose> <c:when test="${empty alerts}"> <p class="text-default">There are no Service Reminders at this time</p> ...

Retrieve JSON information utilizing a specific value stored in the localStorage

After an extensive search online yielded no results, I decided to seek assistance here. This is what I have managed to gather so far: JSON I possess a JSON file containing various lists of words that require retrieval based on user input. The structure ...

Can someone assist me with troubleshooting my issue of using a for loop to iterate through an array during a function call

Having recently delved into the world of Javascript, I've encountered a challenging problem that has consumed my entire day. Despite attempting to resolve it on my own, I find myself feeling quite stuck. The structure of my code is relatively simple ...

Verify whether the type of the emitted variable aligns with the specified custom type

Currently, I am in the process of testing Vue 3 components using jest. My main objective is to receive an emit when a button is clicked and then verify if the emitted object corresponds to a custom type that I have defined in a separate file. Below is an e ...

Create an interactive JSON tree structure

I am looking to create a JSON tree from an array. My array is structured like this: var arraySource = []; arraySource.push({key : "fr", value: "france"}); arraySource.push({key : "es", value: "spain"}); //... console.debug(arraySource); The desired JSON ...

Various style sheets are used for the production and staging environments

Is there a way to set up different styles for staging in node environments? Let's say I have the following scss files: scss/style.scss scss/theme.scss scss/green.scss After compiling, it gives me: style.scss Now, I'd like to change the style ...

Implementing checkboxes for each API data in JavaScript

I am fairly new to this and I am currently working on a to-do list. I want to include a checkbox next to each item from the API to indicate whether it has been completed or not. <script type="text/javascript"> fetch('http://localhos ...

When attempting to display an updated value in a dialog window using an ajax response for the second time, the change

Upon submission of my form, a PHP script is triggered via AJAX to perform validation. Currently, the script simply echoes the post value. For example, if a user inputs "Dog" into "formEntry," the AJAX response will display Dog. However, if the user cancels ...

Executing Javascript requests on a php server hosted on the web

I'm facing a major issue in my application. I have an app that interacts with a PHP webservice and retrieves data upon button press. However, the service is unresponsive, and I'm struggling to identify the root cause. My intention is to send &ap ...

Implementing the session injection into a request body within an asynchronous function in Node.js

I've been trying to inject a session value into the request in order to use it in various parts of my app. What I'm currently attempting is to call a function by providing an ID to search for a user in the database and retrieve the name of that s ...