how to redirect to child route in nuxt?
Asked Answered
L

4

6

i want to redirect to child route, if user entered to localhost:3000/browse, he redirect to localhost:3000/browse/songs/new. but i don't know how to do it!

and i don't know what is the best component structure for this example

my routes will be like this:

localhost:3000/browse/songs/new
localhost:3000/browse/songs/popular
localhost:3000/browse/songs/top
localhost:3000/browse/songs/podcasts
localhost:3000/browse/songs/playlist

and in all of theme, i have a common section, but contents are difrent.

common section

Loyceloyd answered 9/4, 2019 at 19:10 Comment(0)
N
12

If you only have one location to redirect to, check out Andrew1325's answer. If there are multiple route-to-redirect match-ups, this thread has some ideas.

The way I do it is with "anonymous" middleware, like so:

In /pages/browse/index.js

<script>
export default {
    middleware: [
        function({ redirect }) {
            redirect('/browse/songs/new');
        },
    ],
};
</script>
Neolith answered 4/3, 2020 at 16:11 Comment(1)
Add the checks as mentioned in @Miracool's answer to avoid the circular redirection.Zermatt
J
6

To redirect automatically or under certain conditions you need to use middleware. This can be setup like this:

//browse/index.js
<template>
  //no need for content as redirecting
</template>

<script>
export default {
  middleware: 'redirect'
}
</script>

and your middleware file...

//middleware/redirect.js
export default function ({ store, redirect }) {
  // automatic redirect
  return redirect('/browse/songs/new')
}

Read about middleware here

Your pages structure is set up in the pages folder and you name folders and pages as you would like your routes to be.

Read about it here

To use a common theme you can use layouts. These will have a <nuxt-child/> section which will display the individual page content.

You can read about them here

All of this is pretty basic nuxt stuff, you should take some time to read the documantation or look at some tutorials listed here.

Jacobian answered 9/4, 2019 at 21:2 Comment(0)
A
2

Big ups to @parker_codes, there is a little deficiency is his implementation which is circular redirection a.k.a forever redirect loop.

To solve this, add some checks in the parent component. This is because Nuxt Js calls the middleware of a parent route anytime a child route is visited.


//browse/index.js
<template>
  //no need for content as redirecting
  <NuxtChild />
</template>

<script>
export default {
  middleware({ route, redirect, from }) {
    if(route.path == "/browse" || route.path == "/browse/"){
     return redirect("/browse/songs/new")
    }

  }
}
</script>

Abusive answered 19/6, 2021 at 11:25 Comment(0)
E
0

This is also nice solution.

<script setup>
definePageMeta({
  redirect: "/browse/songs/new",
});
</script>
Extend answered 21/8, 2023 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.