返回按钮问题(无法返回历史的上一级)
我们通过浏览器进行返回的时候,发现没有历史记录,一开始我根据i18n针对两个语言做了plugins 全局路由配置
代码如下:
export default ({ app, $cookies }) => {
const router = app.router;
router.beforeEach((to, from, next) => {
// 获取当前选中的语言(优先从cookie获取,若无则使用默认语言)
const currentLanguage = $cookies.get('i18n_redirected') || 'zh';
// 如果是默认语言或目标路径已包含正确前缀,则直接跳转
if (currentLanguage === 'zh' || to.fullPath.startsWith(`/${currentLanguage}`)) {
next();
return;
}
// 获取对应语言的前缀,并构建正确路径
const languagePrefix = `/${currentLanguage}`;
const prefixedPath = `${languagePrefix}${to.path}`;
const prefixedQuery = { ...to.query }; // 复制原有查询参数
// 检查新路径是否与当前路径不同,如果是则进行跳转
// ...
let shouldRedirect = false;
if (currentLanguage !== 'zh' && !to.fullPath.startsWith(`/${currentLanguage}`)) {
// 当目标路径没有正确语言前缀时才设置为需要重定向
shouldRedirect = true;
}
// 合并新的路径与查询参数
const newRoutePath = {
path: prefixedPath,
query: prefixedQuery
};
if (shouldRedirect) {
try {
const targetRoute = router.resolve(newRoutePath);
// 使用 router.push() 替换 router.replace()
// 这样可以确保每次路由变更都会被添加到浏览器历史记录中
router.push(newRoutePath)
} catch (err) {
console.error('An error occurred during navigation:', err);
}
// 不再调用 next(),因为已经通过 router.push() 更新了路由和历史记录
} else {
next();
}
});
// 监听浏览器的返回事件
window.addEventListener('popstate', () => {
// 在这里重新检查当前页面的语言和存储在cookie中的语言是否一致
// 这部分逻辑可以根据您的实际需求进行调整或移除
// 因为nuxt-i18n模块本身应能处理好历史记录中的语言切换
});
};
router.push(newRoutePath) 发现这里出现问题:之前使用的是router.replace无法获取到历史记录
已解决