Nuxt 设置路由基础路径
Nuxt文档
Nuxt 设置路由基础路径
背景
运维希望设置路由的基本路径,所有路由带上前缀 /location
:
http://10.10.8.24:4100/
=> http://10.10.8.24:4100/location/
解决方案
方案一
将 src/
下的所有文件扔到 src/location/
文件夹下,暴力解决,改动成本很大,不推荐
方案二
通过配置文件的 router.base 设置 nuxt.config.js
router: { // 路由的中间件,页面加载之前调用,此时模板已经生成
base: '/location',
middleware: 'router',
extendRoutes(routes, resolve) {
routes.push({
path: '/home/index',
redirect: '/'
});
}
},
发现的问题
本地使用 <a>
标签跳转 /about?type=dynamic
时,vscode 控制台会提示
ℹ [Development] Redirecting from /about/dynamic-detail/263 to /location/about/dynamic-detail/263 (router.base specified)
注意前缀 Development
,也就是说只在开发环境生效,全局搜索关键词,在 node_modules/@nuxt/server/dist/server.js 中发现相关代码
// DX: redirect if router.base in development
const routerBase = this.nuxt.options.router.base;
if (this.options.dev && routerBase !== '/') {
this.useMiddleware({
prefix: false,
handler: (req, res, next) => {
if (decodeURI(req.url).startsWith(decodeURI(routerBase))) {
return next()
}
const to = utils.urlJoin(routerBase, req.url);
consola__default['default'].info(`[Development] Redirecting from \`${decodeURI(req.url)}\` to \`${decodeURI(to)}\` (router.base specified)`);
res.writeHead(302, {
Location: to
});
res.end();
}
});
}
注意事项!
由于项目中使用了 router.base
配置(见 nuxt.config.js 的 router 配置项),进行本地路由跳转要特殊处理,以跳转到 /about?type=dynamic
为例
- 使用
<nuxt-link>
标签跳转路由时,千万不要手动加上/location
前缀,to="/about?type=dynamic"
会自动跳转到/location/about?type=dynamic
, - 使用
<a>
标签跳转本地路由时,一定要加上/location
前缀,如href="/location/about?type=dynamic"
,因为本地会重定向到/location/about?type=dynamic
,但是发到线上不会进行重定向 - 基于上述两种情况,对于需要同时判断跳转外部链接和内部路由的场景(如 pages/about/components/Dynamic.vue),建议直接使用
LinkTo
组件的 href、to 属性
LinkTo 组件封装了 <nuxt-link>
和 <a>
标签,使用时不需要做特殊处理,外部链接传入 href 属性,内部路由传入 to 属性。