Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass props to a page in Nuxt?

Tags:

vue.js

nuxt.js

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

like image 934
ccleve Avatar asked Feb 28 '20 00:02

ccleve


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

like image 89
Alfonz Avatar answered Nov 03 '22 20:11

Alfonz