Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to redirect to child route in nuxt?

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

like image 468
mr stark Avatar asked Dec 13 '22 12:12

mr stark


2 Answers

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>
like image 165
parker_codes Avatar answered Dec 18 '22 14:12

parker_codes


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.

like image 25
Andrew1325 Avatar answered Dec 18 '22 14:12

Andrew1325