如何在Nuxt3中添加带/g/前缀的自定义路由且避免代码重复?
带/g/前缀的路由复用解决方案(不复制页面、不重定向)
针对Nuxt.js(适配Nuxt2/Nuxt3)
Nuxt2 配置方式
在项目根目录的nuxt.config.js中扩展路由规则,自动给现有路由添加/g/前缀的副本,复用原页面组件:
export default { extendRoutes(routes, resolve) { // 遍历原路由,生成带/g/前缀的新路由 const gPrefixRoutes = routes.map(route => { // 跳过已有的/g/路由,避免循环生成 if (route.path.startsWith('/g/')) return null // 处理根路由,其他路由直接拼接/g/前缀 const newPath = route.path === '/' ? '/g/' : `/g${route.path}` return { ...route, path: newPath, component: route.component // 直接复用原组件,无需复制文件 } }).filter(Boolean) // 过滤空值 // 将新路由合并到路由列表 routes.push(...gPrefixRoutes) } }
Nuxt3 配置方式
在app/router.options.ts中自定义路由规则:
import type { RouterConfig } from '@nuxt/schema' export default <RouterConfig>{ routes: (originalRoutes) => { // 生成带/g/前缀的路由副本 const gRoutes = originalRoutes.map(route => ({ ...route, path: route.path === '/' ? '/g/' : `/g${route.path}` })) // 合并原路由与新路由 return [...originalRoutes, ...gRoutes] } }
针对纯Vue项目(Vue Router)
在router/index.js中手动构建路由列表,同时包含原路由和带/g/前缀的路由:
import Vue from 'vue' import VueRouter from 'vue-router' // 导入原页面组件 import Home from '../views/Home.vue' import ProductsIndex from '../views/products/index.vue' import ProductsDetail from '../views/products/[id].vue' import BlogsIndex from '../views/blogs/index.vue' import BlogsDetail from '../views/blogs/[id].vue' Vue.use(VueRouter) // 定义原路由 const originalRoutes = [ { path: '/', name: 'Home', component: Home }, { path: '/products/', name: 'ProductsIndex', component: ProductsIndex }, { path: '/products/:id', name: 'ProductsDetail', component: ProductsDetail }, { path: '/blogs/', name: 'BlogsIndex', component: BlogsIndex }, { path: '/blogs/:id', name: 'BlogsDetail', component: BlogsDetail } ] // 生成带/g/前缀的路由,复用原组件 const gPrefixRoutes = originalRoutes.map(route => ({ ...route, path: route.path === '/' ? '/g/' : `/g${route.path}`, name: `g-${route.name}` // 修改name避免路由名称冲突 })) // 合并路由 const routes = [...originalRoutes, ...gPrefixRoutes] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
关键说明
- 所有带
/g/前缀的路由直接复用原页面组件,完全不用复制pages目录或文件 - 访问
/g/、/g/products/等URL时,地址栏不会重定向,保持前缀路径 - 动态路由(如
/products/:id)会自动继承匹配规则,/g/products/1这类路径也能正常匹配
内容的提问来源于stack exchange,提问作者yasuda_t
相关产品推荐
相关产品推荐

