Vue监听浏览器的后退与前进按钮
// 检查浏览器是否支持history API
if (window.history && window.history.pushState) {
// 如果支持,给window添加popstate监听事件,用于监听后退按钮的点击
window.addEventListener('popstate', goBack, false);
}
// 在IE中,为了确保后退按钮可以触发popstate事件,必须执行以下两行代码
window.history.pushState('forward', null, '');
window.history.forward(1);
// 定义后退按钮的回调函数
function goBack() {
// 获取url历史记录
let history = store.state.urlHistory;
// 判断历史记录的长度
if(history.length > 1) {
// 如果历史记录长度大于1,则跳转到倒数第三个历史记录的url
router.push(history[history.length - 3]);
} else {
// 否则,跳转到首页
router.push('/');
}
// 再次执行以下两行代码,确保后退按钮可以再次触发popstate事件
window.history.pushState('forward', null, '');
window.history.forward(1);
}
// 当Vue组件销毁前,移除popstate的监听事件,以免造成内存泄漏
onBeforeUnmount(() => {
window.removeEventListener('popstate', goBack, false);
})