【问题标题】:Use same page for multiple routes对多条路线使用同一页面
【发布时间】:2020-05-27 16:45:17
【问题描述】:

我正在尝试找出如何在带有 i18n 模块的 Nuxt.js 上将同一页面用于多个路由。

基本上我希望这条路线:/product-category/:slug/in/:material 使用与/product-category/:slug 相同的页面

到目前为止,我已经在下面尝试过,将其添加到 nuxt.config.js - 但它不起作用。它只是显示_slug/_material/index.vue 文件。

router: {
    extendRoutes (routes, resolve) {
        routes.push({
            path: '/product-category/:slug/in/:material',
            component: resolve(__dirname, 'pages/product-category/_slug/index.vue')
        })
    }
},

也许是因为我有 i18n 模块,也许是因为我做错了什么。

这是我的文件夹结构:

如果我检查我的 router.js 文件,我会看到两次显示的路径:

【问题讨论】:

  • “但它不起作用” - 究竟是什么意思?
  • @MichalLevý 我已经用更准确的信息更新了我的问题。 tldr;它显示了_slug/_materiale/index.vue 文件

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


【解决方案1】:

这是我的解决方法,我只是希望有一个更简单的方法。另外,如果您使用 nuxt i18n,它仍然有效。

nuxt.config.js

router: {
    extendRoutes (routes, resolve) {
        const routesToAdd = [
            { // add your routes here
                name: 'product-category-slug-material',
                path: '/product-category/:slug/in/:material',
                component: resolve(__dirname, 'pages/product-category/_slug/index.vue'), // which component should it resolve to?
                chunkName: 'pages/product-category/_slug/_material/index' // this part is important if you want i18n to work
            }
        ];

        const existingRoutesToRemove = routesToAdd.map(route => route.name);

        const generateRoutes = routes.filter((route) => {
            return !existingRoutesToRemove.includes(route.name);
        });

        routesToAdd.forEach(({ name, path, component, chunkName }) => {
            generateRoutes.push({
                name,
                path,
                component,
                chunkName
            });
        });

        routes.splice(0, routes.length, ...generateRoutes); // set new array
    }
},

【讨论】:

    【解决方案2】:

    您可以使用_.vue 捕获所有内容。

    如果你不知道你的 URL 结构的深度,你可以使用 _.vue 来动态匹配嵌套路径。这将处理与更具体的请求不匹配的请求。

    Here你可以了解更多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-04
      • 1970-01-01
      • 2014-03-04
      • 2017-01-09
      • 2021-06-07
      • 2017-04-21
      • 1970-01-01
      相关资源
      最近更新 更多