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
The easiest way I've found is to use named routes along with the params options. Let's say you have a router file that looks like this:
And you want to reach the "movie" page with some ID. You can use Vue's router link component (or Nuxt's link component) to reach it like this:
Vue:
Nuxt:
Note that the name parameter must match the "name" attribute of the desired route in the router file. And likewise, the parameter name must match.
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 objectso your routes should be
Then for programmatically navigating to the component you should do:
See that I am using
name
of the route instead ofpath
as you are passing params by the propertyparams
.if you want to use
path
then it should be: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"}
Try using query instead of params
And in your component
Isn't it generally considered an anti pattern to bind the properties to the router?
It's a much more DRY solution to have them bind to the component it's self, which I actually believe the Vue router does. Please see: https://router.vuejs.org/en/essentials/passing-props.html for more info on the best practices here
Can you try accepting the property in the props: [] property of your component? You can see how to do that here: https://vuejs.org/v2/guide/components.html#Props
Please do pop up if you have any questions! Happy to help further.