14

I have a sample Vue router here which handles going to the login first before accessing the form with a specific id:

router = new VueRouter({
             routes: [
                 {path: '/form/:id', redirect: '/login'},
                 {path: '/login', name: 'Login', component: Login}
             ]
         });

Is there a way that the login can still access the :id parameter passed since when I run http://localhost:8080/form/c101-101 it directly redirects to the Login component and when I try to log this.$route.params.id inside the login component it's undefined. Is there a way I can pass the :id on redirect?

2 Answers 2

23

You can use a function for dynamic redirecting, as per the Vue docs.

Here's an example taking a param (e.g. yourdomain.com/:yourParam) and redirecting to another URL, using the param (yourParam) as a query string (yourdomain.com/your/route?yourQueryString=:yourParam):

redirect: to => ({
  name: "your-named-route",
  query: { yourQueryString: to.params.yourParam },
}),

note: this syntax is using ES6.

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

2 Comments

how to use it into a function when a click has been fired?
Instead of forwarding the parameter as a query parameter (and I don't see that the OP asked for that) you can use redirect: to => ({ path: '/form/' + to.params.id }),
8

You can make /:id as optional in login routes as follows:-

router = new VueRouter({
         routes: [
             {path: '/form/:id', redirect: '/login/:id'},
             {path: '/login/:id?', name: 'Login', component: Login}
         ]
     });

With above snippet of code you will get this.$route.params.id in login component.

3 Comments

One caveat about this approach: if one needs to keep both /feature and /feature/:id as separate routes (which is an often used pattern for list and edit pages), using /feature/:id? would supersede /feature, so it wouldn't be an applicable solution in this scenario.
This does not work anymore in 2023/24
Yeah I think the workaround would be to use pass a function as render (dynamic routing) see router.vuejs.org/guide/essentials/…

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.