VueRouter child route with trailing slash after default

VueRouter automatically includes a trailing slash before the child route's path. Consider this example of a route configuration:

const routes = [
    path: '/home',
    components: {
        default: HomeBase
    },
    children: [
        {
            path: '',
            component: HomeIndex,
            name: 'home.index'
        },
        {
            path: ':aid',
            component: HomeArticle,
            name: 'home.article'
        }
    ]
]

I would like the routes to function as follows:

  • /home -> loads HomeIndex
  • /home/123 -> Loads HomeArticle with :aid=123

However, VueRouter consistently adds a trailing slash to the parent route path when accessing a child route, resulting in the following behavior:

  • /home/ -> loads HomeIndex
  • /home/123 -> loads HomeArticle with :aid=123

This poses an issue for me because I am working on an application that has specific SEO requirements mandating no trailing slashes.

It is important to note that I am utilizing named routes for URL generation and route navigation to maintain DRY code practices. While linking directly to "/home" is possible, using route names (e.g., "home.index") is preferred. Storing paths in constants could be an alternative solution, but it restricts the ability to use the 'params' prop alongside the 'path' prop during programmatic navigation.

One potential approach could involve separating HomeIndex as a distinct path rather than making it a child route. However, both HomeIndex and HomeArticle must be loaded within the root HomeBase component.

Are there any suggestions on how I can address this concern? Perhaps through VueRouter hooks or plugins?

Answer №1

My solution involved implementing the following structure:

const routes = [
    path: '/home',
    components: {
        default: HomeBase
    },
    children: [
        {
            path: '/home',
            component: HomeIndex,
            name: "homeindex"
        },
        {
            path: ':aid',
            component: HomeArticle,
            name: "aid"
        }
    ]
]

To see a working example, check out this fiddle

The code was tested using versions: Vue - 2.5.2, vue-router - 3.0.1. Both named and path-based routing worked seamlessly without requiring a trailing slash at the end, for instance:

this.$router.push({name: "homeindex"})

this.$router.push("/home")

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

Encountered an error with Winston and Elasticsearch integration: "TypeError: Elasticsearch is not a constructor

I recently implemented winston-elasticsearch on my express server by following the code provided in the documentation var winston = require('winston'); var Elasticsearch = require('winston-elasticsearch'); var esTransportOpts = { le ...

What is the method to retrieve values passed to the next() function in Node.js?

For my current project, I am utilizing Node.js in combination with Express.js to develop the back-end. In middleware functions, next() is commonly used to progress through the chain until reaching the final app.VERB() function. My question is, at what poi ...

Is Angular automatically assigned to `window.angular` on a global level when it is loaded as a CommonJS module?

When I import Angular 1.4 in my Webpack build entry point module as a CommonJS module using var angular = require("angular");, it somehow ends up being accessible in the global namespace of the browser (as window.angular). Upon examining the source code o ...

What is the best way to access data from outside a forEach loop in JavaScript?

I am trying to access the value of my uid outside of the foreach loop in my code. Can anyone assist me with this? This is the code I am working with: var conf_url = "https://192.168.236.33/confbridge_participants/conference_participants.json?cid=009000 ...

I keep encountering the following error message: " ERROR Error Code: 200 Message: Http failure during parsing for http://localhost:3000/login"

My Angular Login component is responsible for passing form data to the OnSubmit method. The goal is to send form data from the front-end application and authenticate users based on matching usernames and passwords in a MySQL database. ***This login form i ...

Error encountered when connecting to MongoDB: 'MongoServerSelectionError'

const uri = 'mongodb+srv:<username>//:<passwod>@chatapp-qrps3.azure.mongodb.net/test?retryWrites=true&w=majority' const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }) client.c ...

Alert-Enabled Random Number Generation Tool

I'm struggling to create a program that randomly generates a number between 1 and 20. If the number is less than 10, it should display "fail," and if it's greater than 10, it should display "success." I can't seem to figure out where I went ...

Currently, I am experiencing difficulties with two specific aspects of the website I am working on - the hamburger menu and the slideshow feature

I'm having trouble with the menu on my website. It's not functioning as expected - the dropdown feature isn't working, and two items are not staying in the correct position under the parent ul despite attempts to position them using CSS. Add ...

Accessing a service instance within the $rootScope.$on function in Angular

I'm looking for a way to access the service instance variable inside the $rootScope in the following code. myapp.service('myservice',function($rootScope) { this.var = false; $rootScope.$on('channel',function(e,msg) { v ...

Achieving success in element-ui vuejs involves validating the state with the :error parameter

I recently developed an app using Laravel, Vuejs, and Element-ui. Within my form, I have utilized the "error" property to indicate that Laravel validation is in place. <el-form-item label="First Name" prop="firstname" :error="registerForm.errors.get(&a ...

What is the best way to obtain a user's ID on the server side?

I'm currently working on a node.js application using express and I am in need of retrieving the user ID. I would like to have something similar to "req.userID" so that I can use it in the following way: var counter=0; var user = new Array(); router.g ...

Looking through a Json file and retrieving data with the help of Javascript

I am currently working on developing a dictionary application for FirefoxOS using JavaScript. The structure of my JSON file is as follows: [ {"id":"3784","word":"Ajar","type":"adv.","descr":" Slightly turned or opened; as, the door was standing ajar.","tr ...

Choose the radio button by clicking using jQuery

I am attempting to use jQuery to select a radio button on click. Despite multiple attempts, I have been unsuccessful so far. Here is my current code: JS $(document).ready(function() { $("#payment").click(function(event) { event.preventDefault() ...

What is the best way to make changes to the DOM when the state undergoes a

I've programmed the box container to adjust dynamically based on input changes. For instance, if I entered 1, it will generate one box. However, if I modify the input to 2, it mistakenly creates 3 boxes instead of just 2. import React from 'rea ...

HTML form with a dropdown menu

Imagine you have a HTML form containing two dropdown lists. The first dropdown is labeled "country" and contains a list of countries. The second dropdown, labeled "cities," should be dynamically populated based on the country selected. What is the best ...

HTML5 canvas processing causing web worker to run out of memory

Within the Main thread: The source image array is obtained using the getImageData method. It is represented as a uint8ClampedArray to store the image data. Below is the code executed in a web worker: (This operation generates a high-resolution image, but ...

The issue of linking .then() functions

I've been struggling to grasp the concept of Promises/then-ables for a while now. Currently, I am working with NextJS. My goal is to chain together the following steps: Retrieve data from an API Save the data Modify the data to create a component (w ...

Is there a way to set the starting position of the overflow scroll to the middle?

Is there a way to have the overflow-x scrollbar scroll position start in the middle rather than on the left side? Currently, it always begins at the left side. Here is what it looks like now: https://i.stack.imgur.com/NN5Ty.png If anyone knows of a soluti ...

Having trouble connecting the controller variable in AngularJS to the HTML page

I'm struggling with a simple query that doesn't seem to be working for me. When making an Ajax call and retrieving data from the backend, everything seems to be in order. Here's the code snippet: $.ajax({ type: "GET", url: service ...

Having trouble sending specific data using the jQuery Form Plugin ajaxForm feature

Currently, I am utilizing two jQuery plugins: plupload and jQuery Form Plugin ajaxForm. Everything is functioning well except for one issue: I am unable to send the file.name (using ajaxForm) of a previously uploaded file with plupload. To elaborate more ...