我正在从 Vue router Doc 学习相对重定向。
我正在尝试实现代码的文档示例。
const routes = [
{
// will always redirect /users/123/posts to /users/123/profile
path: '/users/:id/posts',
redirect: to => {
// the function receives the target route as the argument
// a relative location doesn't start with `/`
// or { path: 'profile'}
return 'profile'
},
},
]
在我对代码的理解中。 它说当链接路径是/user/123/posts
最终重定向路径将是 /user/123/profile 而不是 /profile。
所以我的代码路径的 URL 相同: http://localhost:5173/maxroll-build/S/roll >> http://localhost:5173/maxroll-build/S/roll 但真正的路径最终是http://localhost:5173/gg
我尝试了很长时间的方法。其中,我发现了一个和我几乎一模一样的问题(相对重定向错误#1902)。 但我仍然没有完全意识到如何编写相对重定向。有代码演示吗
或者也许文档仍然含糊不清?
我的代码:
// router/index.js
const routes = [
// ... other route
{
path: "/maxroll-build/:buildLevel/roll",
redirect: (to) => {
console.log("to ", to);
// console of to.fullPath: "/maxroll-build/S/roll"
return { path: "gg" }; // here finally web link: http://localhost:5173/gg
},
},
{
path: "/maxroll-build/:buildLevel/gg",
component: MaxRollLevel,
},
// ... other route
];
要实现相对重定向,您需要从重定向函数返回一个相对路径,不带前导/。以下是修改代码的方法:
const routes = [
{
path: "/maxroll-build/:buildLevel/roll",
redirect: (to) => {
console.log("to ", to);
// Redirect to the relative path 'gg' without leading '/'
return "gg";
},
},
{
path: "/maxroll-build/:buildLevel/gg",
component: MaxRollLevel,
},
// Other routes
];