如果params
的名称是特定名称,并且我不知道为什么这不起作用,我想替换to
的to
之一。
export const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
scrollBehavior() {
return { x: 0, y: 0 };
},
routes: [
{
name: 'Details Page',
path: 'details/:name/:id',
component: () => import('@/views/Details.vue'),
meta: {
encode: true,
},
},
// other routes... (none of them has encode = true)
]
});
function needsEncode(route) {
return route.meta && route.meta.encode;
}
router.beforeEach(async (to, from, next) => {
if (to.name === 'Details Page' && needsEncode(to)) {
const toEncoded = Object.assign({}, to, {
meta: {
encode: false,
},
params: {
name: encodeURIComponent(to.params.name),
id: to.params.id,
},
});
return next(toEncoded);
}
return next();
}
我在做什么错?
请不要将状态存储在meta
属性中。相反,您可以检查名称是否已编码:
function needsEncode(route) {
return route.meta && route.meta.encode && ( // <-- changes start here
decodeURIComponent(to.params.name) === to.params.name
) // <-- changes ends here
}
router.beforeEach(async (to, from, next) => {
if (to.name === 'Details Page' && needsEncode(to)) {
const toEncoded = Object.assign({}, to, {
// remove meta
//meta: {
// encode: false,
//},
params: {
name: encodeURIComponent(to.params.name),
id: to.params.id,
},
});
return next(toEncoded);
}
return next();
}
如果decodeURIComponent(to.params.name)
等于名称,则尚未对其进行编码,您可以继续对其进行编码。