【问题标题】:how to redirect to child route in nuxt?如何重定向到nuxt中的子路由?
【发布时间】:2019-08-31 03:40:47
【问题描述】:

如果用户输入localhost:3000/browse,我想重定向到子路由, 他重定向到localhost:3000/browse/songs/new。 但我不知道该怎么做!

我不知道这个例子最好的组件结构是什么

我的路线会是这样的:

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

在所有主题中,我有一个共同的部分,但内容不同。

common section

【问题讨论】:

    标签: vue.js vue-router nuxt.js


    【解决方案1】:

    如果您只有一个要重定向的位置,请查看 Andrew1325 的答案。如果有多个路由重定向匹配,this thread 有一些想法。

    我这样做的方式是使用“匿名”中间件,如下所示:

    在 /pages/browse/index.js 中

    <script>
    export default {
        middleware: [
            function({ redirect }) {
                redirect('/browse/songs/new');
            },
        ],
    };
    </script>
    

    【讨论】:

      【解决方案2】:

      要自动或在特定条件下重定向,您需要使用中间件。可以这样设置:

      //browse/index.js
      <template>
        //no need for content as redirecting
      </template>
      
      <script>
      export default {
        middleware: 'redirect'
      }
      </script>
      

      还有你的中间件文件...

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

      了解中间件here

      您的页面结构设置在 pages 文件夹中,您可以根据自己的路线命名文件夹和页面。

      阅读here

      要使用通用主题,您可以使用布局。这些将有一个&lt;nuxt-child/&gt; 部分,它将显示各个页面的内容。

      你可以阅读他们here

      所有这些都是非常基本的 nuxt 内容,您应该花一些时间阅读文档或查看列出的一些教程 here

      【讨论】:

        【解决方案3】:

        感谢@parker_codes,他的实现有点不足,即循环重定向,也就是永远的重定向循环。

        要解决这个问题,请在父组件中添加一些检查。这是因为Nuxt Js 在每次访问子路由时都会调用父路由的中间件。

        
        //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>
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-07-06
          • 1970-01-01
          • 2017-08-10
          • 2017-08-21
          • 1970-01-01
          • 2021-04-14
          • 2018-10-22
          相关资源
          最近更新 更多