ccleve
ccleve

Reputation: 15779

How to pass props to a page in Nuxt?

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.)

Upvotes: 8

Views: 14610

Answers (3)

Theiaz
Theiaz

Reputation: 784

I've found help at the nuxt discord channel. Here is the link for future references: https://discord.com/channels/473401852243869706/1293875986907004968

TLDR: The coupling between the nuxt page and the router is already implicit, so an explicit coupling is no big deal.

The guide is about not linking components to the router. This does not necessarily include pages at nuxt.

You could just bind the route params from page level into the component and leave the component unaware of the route and page if reusability is a thing.

Upvotes: 1

user12531597
user12531597

Reputation:

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);
}

Upvotes: -1

Alfonz
Alfonz

Reputation: 1020

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.

Upvotes: 2

Related Questions