How to pass props to a page in Nuxt?

Viewed 10543

All I'm trying to do is pass a parameter to a page in Nuxt. In Vue, it's easy:

<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>

or

<router-link to="/user/123">User</router-link>

You just need to define your route correctly in router.js.

I haven't found a way to do it in Nuxt.

There is some reference in the Nuxt documentation to using underscores to define dynamic routes here, which is just strange. How do you pass more than one prop? What if you don't want to mess up your page naming conventions?

But in any case, it simply does not work. It appears to be possible to get the value of the parameter only by accessing this.$route.params.myprop, which is bad practice as explained here.

So how do I set up route "/users/123", invoke the Users.vue component in /pages, and actually get "123" as a prop?

(No, I'm not going to use VueX. It's very poor practice to use global state simply to pass parameters.)

2 Answers

The underscore filename system is the recommended way to create dynamic routes on Nuxt.js.

How do you pass more than one prop?

The documentation has a section for dynamic nested routes:

pages/
--| _category/
-----| _subCategory/
--------| _id.vue
--------| index.vue
-----| _subCategory.vue
-----| index.vue
--| _category.vue
--| index.vue

This will give you a :category/:subCategory/:id route.

Also, you can use extendRoutes in nuxt.config.js, or the router-module if you want to avoid using the default Nuxt generated routes altogether.

Do you mean something like this?

<nuxt-link to="/user/:id">User</nuxt-link>

and now type in the url bar

http://yourDomain/user/123

And in the created lifecycle hook in the page user you should see the console log of 123

created(){
   console.log("your id is: " + this.$route.params.id);
}
Related