How to use vue-router params

Viewed 85888

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 a new object {}.

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

4 Answers

Try using query instead of params

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

And in your component

console.log(this.$route.query.foo)

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:

Vue Router File

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:

<router-link :to="{ name: 'movie', params: { id: item.id } }">{{ item.title }}</router-link>

Nuxt:

<nuxt-link :to="{ name: 'movie-id', params: { id: item.id } }">{{ item.title }}</nuxt-link>

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.

Nuxt creates the route file for you automatically when you create a new page. To see what name Nuxt gives its routes, go to the .Nuxt folder in your project and look for a "router.js" file

Related