Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters on redirecting using Vue Router

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?

like image 262
The Bassman Avatar asked Apr 20 '18 04:04

The Bassman


People also ask

How do I redirect a URL in Vue?

If you're using Vue Router you'll push the new URL onto the router in order to do a redirect: this. $router. push('www.yoursite.com/blog') .

How do you access parameters in Vue?

We can access the params object inside of the Profile component through the $route object.

How do I create a dynamic route Vue?

Adding dynamic routes in VueUpdate the router/index. js file with the new route in the routes array. Remember to include the import for the Post component. Restart your app and head to localhost:8080/post/dynamic-routing in your browser.


2 Answers

For those still coming through to this, 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.

like image 134
fredrivett Avatar answered Sep 27 '22 19:09

fredrivett


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.

like image 24
Sagar Kharche Avatar answered Sep 27 '22 19:09

Sagar Kharche