我是在这篇博客vue router路由自定义后退事件的基础之上,经过自己的一些修改做出来的
// 相当于一个页面栈
window.routerList = [];
router.afterEach((to, from) => {
window.back = function() {
window.router.isBack = true;
if (window.routerList.length == 0) {
window.router.isBack = false;
return;
} else if (window.routerList.length == 1) {
window.router.isBack = false;
console.log('不能后退了!!!');
} else {
let backPath = window.routerList[window.routerList.length - 2].fullPath;
window.router.push(backPath);
}
}
// 如果要去的页面已经存在于页面栈中,就相当于回退
if (!window.router.isBack) {
var routerListLen = window.routerList.length
if (routerListLen > 1 && window.routerList.findIndex(item => item.path == to.path)!== -1) {
window.router.isBack = true;
}
}
/*
* 如果是后退,将当前页面从list中删除
* 如果是前进,将当前页面添加到list中
*/
if (window.router.isBack) {
window.routerList.pop();
console.log('后退', window.routerList)
} else {
let isExistPathIndex = window.routerList.findIndex(item => item.path == to.path)
if (isExistPathIndex !== -1) {
window.routerList = window.routerList.slice(0, isExistPathIndex)
}
window.routerList.push({
path: to.path,
fullPath: to.fullPath
});
console.log('前进', window.routerList)
}
});
window.router = router;
在页面中,跳转路由还是使用 this.$router.push()
,页面回退改为window.back()