用vue3开发的的移动端项目ios无法回退怎么解决?

215 阅读1分钟

接之前写的文章 国企的app前端是怎么做的?献给外包到国企的小伙伴们 - 掘金 (juejin.cn) 开发项目的过程中遇到了一个非常诡异的bug,在我们使用vue3+vite+typescript 和vue3+webpack的两个项目的过程中我们都遇到了。

点击页面的后退按钮,ios无法回退的诡异bug

也就是说router.back() router.go(-1) 这些方法都不能用了,尝试了很多次浪费了很多时间,最终只能使用一个兼容性的办法


export function backPre() {  
const currentRouteName = router.currentRoute.value.name;  
const currentRoutePath = router.currentRoute.value.path;  
setSessionWebStorageCache('currentRouteName', currentRouteName);  
setSessionWebStorageCache('currentRoutePath', currentRoutePath);  
const pre = backPrePage();  
router.push({ name: pre });  
}  
function backPrePage() {  
let routerArr = getSessionWebStorageCache<any>('routerArr');  
let pre = '';  
if (!routerArr && typeof routerArr !== 'undefined' && routerArr !== 0) {  
// 没有存值  
routerArr = [];  
} else {  
pre = routerArr.pop();  
if (typeof pre !== 'undefined') {  
// $utils.setVal("routerArr", routerArr)  
setSessionWebStorageCache('routerArr', routerArr);  
}  
}  
return pre;  
}


在路由守卫中也添加同样的逻辑

const createRouterGuard = (router: Router) => {  
router.beforeEach((to, from, next) => {  
// let routerArr = JSON.parse($utils.getVal("routerArr"));  
let routerArr = getSessionWebStorageCache<string[]>('routerArr');  
  
if (!routerArr && typeof routerArr !== 'undefined' && routerArr !== 0) {  
//判断为null 没有存值  
routerArr = [];  
}  
  
// 存储上一页  
if (routerArr[routerArr.length - 1] !== from.name) {  
// let currentRouteName = $utils.getVal("currentRouteName");  
const currentRouteName = getSessionWebStorageCache('currentRouteName') || '';  
  
const currentRoutePath = getSessionWebStorageCache('currentRoutePath') || '';  
  
if (currentRouteName !== from.name || currentRoutePath !== from.path) {  
routerArr.push(<string>from.name);  
// $utils.setVal("routerArr", routerArr)  
setSessionWebStorageCache('routerArr', routerArr);  
}  
}  
  
next();  
return true;  
});  
};

这里把路由守卫的逻辑单独提取出来了,也可以不用提取直接 在router.beforeEach中直接写

详细代码可以看一下这个