Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueRouter default child route without trailing slash

VueRouter always adds a trailing slash before the path of the child route. So lets say I have a route config like this:

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

I want the routes to work like this:

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

But VueRouter always forces the trailing slash on the parent route path, when accessing a child route, so the routes work like this:

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

This doesn't work for me, as I'm working with an application that has specific SEO requirements that require no trailing slashes.

Note that I'm using named routes to generate URLs and move between routes, so while I could link to "/home" directly, I want to use the names of routes ( "home.index") so code is more DRY. I could store the paths in constants somewhere, but the drawback of that is that you can't use the 'params' prop together with the 'path' prop when programmatically navigating.

I could split out HomeIndex as a separate path entirely, so its not a child, but I need HomeIndex and HomeArticle both to be loaded within the root HomeBase component.

Any ideas how I could achive this? Maybe through some VueRouter hooks or plugins?

like image 490
Fabis Avatar asked Sep 27 '19 08:09

Fabis


1 Answers

I've tried next structure which worked for me:

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

Here is the working fiddle

Using versions: Vue - 2.5.2, vue-router - 3.0.1. Routing works both using name and path without adding trailing slash at the end, i.e.:

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

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

like image 78
Daniyal Lukmanov Avatar answered Nov 06 '22 16:11

Daniyal Lukmanov