Oswaldo
Oswaldo

Reputation: 3376

Alias for vue route with parameter

I have a user profile route like this /user/Mary/profile where I can see any users profile and I want to create an alias like /me/profile so that the user name parameter is hidden and use a constant instead for that parameter.

Something like:

const myUserName = 'Mike';

export default [
  {
    name: 'user',
    path: 'user/:username',
    alias: 'me',
    component: () => import('components/user-layout'),
    children: [
      {
        name: 'user-profile',
        path: 'profile',
        component: () => import('components/user-profile'),
      },
    ],
  },
];

I'm not sure if above is correct and how I should set the username parameter to the myUserName constant in case of user access /me/profile.

** I DON'T want to username param to be myUserName by default, it will be only in case of user access that route by the /me alias

Upvotes: 4

Views: 2171

Answers (2)

Oswaldo
Oswaldo

Reputation: 3376

Ok, so I ended up by creating another route for /me and didn't make alias or redirected, just a normal route with shared children between it and /user, like this:

import userChildrenRoutes from './user-children.routes';

export default [
  {
    name: 'me',
    path: 'me',
    component: () => import('components/user-layout'),
    children: userChildrenRoutes,
  },
  {
    name: 'user',
    path: 'user/:username',
    component: () => import('components/user-profile'),
    children: userChildrenRoutes,
  },
];

and in beforeEnter hook I can handle the username.

Upvotes: 2

dganenco
dganenco

Reputation: 1616

As far as I understand you can't use alias for dynamic routes. I' suggest you to simply create another root called me and redirect it to /user/yourUserName. I've prepared a sample fiddle.

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/', name: 'home', component: Home },
    { path: '/foo', name: 'foo', component: Foo },
        { path: '/user/:username', name: 'user', component: User, children: [
      {
        name: 'user-profile',
        path: 'profile',
        component: Profile,
      },
    ]},
        {path: '/me', redirect: `/user/${someWhereFromSessionUserName}`}
  ]
});

Upvotes: 1

Related Questions