JeremyW
JeremyW

Reputation: 307

Dynamically adding a prefix to a named route in vue 2 / nuxt 2

Pretty simple question, I am pushing a named route like so:

this.$nuxt.$router.push({ name: "my-named-route-id-foo", params: { id: this.$route.params.id } });

But I want to conditionally add a prefix to this so instead of the resulting URL always going to:

/my-named-route/32/foo

It might go to:

/prefix/my-named-route/32/foo

How do I insert the 'prefix' without resorting to a path route? (because I need to pass params on some of them and I don't want to use a query i.e. ?param=blahblah)

I'm assuming it's probably using a custom middleware function, but I'm just not what to use to achieve what I want.

Upvotes: 1

Views: 864

Answers (1)

Retnilps
Retnilps

Reputation: 243

Move your page "my-named-route" into a created folder named "prefix" in your Pages folder.

You can find more information in this page Nested routes

edit:

To create a dynamic route you need to add an underscore (_) before the .vue file name or before the name of the directory. You can name the file or directory anything you want but you must prefix it with an underscore.

File tree

pages/
--| prefix/
----| my-named-route/
------| _id.vue
------| index.vue
----| my-named-route.vue

OR You can also do the conditional statement in the script where you call the router.push()

if(condition) {
    this.$nuxt.$router.push({ name: "my-named-route-id-foo", params: { id: this.$route.params.id } });
}
else {
    this.$nuxt.$router.push({ name: "prefix/my-named-route-id-foo", params: { id: this.$route.params.id } });
}

Upvotes: 0

Related Questions