Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use vue-router params

I'm new to vue now working with its router. I want to navigate to another page and I use the following code:

this.$router.push({path: '/newLocation', params: { foo: "bar"}}); 

Then I expect it to be on the new Component

this.$route.params 

This doesn't work. I also tried:

this.$router.push({path: '/newLocation'}); this.$router.push({params: { foo: "bar"}}); 

I've inspected the source code a bit and noticed this property gets overwritten with new object {}.

I'm wondering is the params use is other than I think? If not, how to use it?

Thanks in advance

like image 420
Gal Ziv Avatar asked Jul 25 '17 07:07

Gal Ziv


People also ask

How do I get parameters from my router?

Use queryParamMap to access query parameters. Another way to access query paramters in Angular is to use queryParamMap property of ActivatedRoute class, which returns an observable with a paramMap object. Take an example of above URL with multiple parameters.

What is params in vue?

In Vue Router we can use a dynamic segment in the path to achieve that, we call that a param: const User = { template: '<div>User</div>', } // these are passed to `createRouter` const routes = [ // dynamic segments start with a colon { path: '/users/:id', component: User }, ]


1 Answers

Since you want to pass params to the component of the respective route you route object's path property should have a dynamic segment denoted by : followed by the name of the key in your params object

so your routes should be

routes: [     {path: '/newLocation/:foo', name: 'newLocation', component: newComponent} ] 

Then for programmatically navigating to the component you should do:

this.$router.push({name: 'newLocation', params: { foo: "bar"}}); 

See that I am using name of the route instead of path as you are passing params by the property params.

if you want to use path then it should be:

this.$router.push({path: '/newLocation/bar'}); 

by the path approach the params will automatically map to corresponding fields on $route.params.

Now if you console.log(this.$route.params) in your new component you will get the object : {"foo": "bar"}

like image 185
Vamsi Krishna Avatar answered Sep 21 '22 11:09

Vamsi Krishna