Nuxt 3 - 如何删除尾部斜杠?

Ron*_*eva 5 nuxt.js nuxtjs3

在 Nuxt 3 中,如何从 url 中删除尾部斜杠?

在 Nuxt 2 中,这是通过将这些行添加到来完成的nuxt.config.js

router: {
    trailingSlash: false
  }
Run Code Online (Sandbox Code Playgroud)

Nuxt 3 中的等效项是什么?

小智 6

根据 @evg_ny 的回答,我创建了这个版本,它将与 Nuxt3 一起使用,将带有尾随斜杠的路由重定向到非尾随斜杠变体:

export default defineNuxtRouteMiddleware((to, from) => {
  if (to.path !== '/' && to.path.endsWith('/')) {
    const { path, query, hash } = to;
    const nextPath = path.replace(/\/+$/, '') || '/';
    const nextRoute = { path: nextPath, query, hash };
    return navigateTo(nextRoute, { redirectCode: 301 });
  }
})
Run Code Online (Sandbox Code Playgroud)

保存它./middleware/redirect-trailing-slash.global.js,它将在全球范围内工作


Fel*_*löf 4

根据nuxt 文档vue router 文档。似乎trailingSlash已被替换为strict“是否禁止尾随斜杠”控制。

但是,根据文档,默认值是false,这意味着在没有任何配置的情况下,您应该能够访问带或不带尾部斜杠的页面。

  • 为了让任何人都更容易,nuxt.config 中的替换代码是 {router:{options:{strict: true}}} (3认同)