4

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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}`}
  ]
});

3 Comments

Thank you very much @dganenco for your dedicated time on this answer, but it doesn't solve my problem because I need to keep showing the /me url for the user instead of redirecting it to /user
In this case you can try to use navigation guards and especially beforeEach() hook. I've updated the fiddle and please let me know if it works. It's a really good question.
thx, I've tried this before and didn't work, I couldn't see /me in browser address bar, I have managed it by creating another independent route as you can see in my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.