表象:
在进行正常页面跳转操作后(页面A跳转到页面B),点击浏览器的左上角的'后退'按钮,点击后,可以看到url地址已经发生了变化(url由页面B变为页面A),hash值也已经是上一页的路由,但是浏览器显示的内容却没有发生变化(依旧是页面B)。
可能的解决办法
1、hash模式的情况
- 了解,hash模式的url相关知识 Vue-Router的Hash说起的URL相关知识
- 通过onhashchange 事件处理
// app.vue 入口处:
mounted () {
// 检测浏览器路由改变页面不刷新问题,hash模式的工作原理是hashchange事件
window.addEventListener('hashchange', () => {
let currentPath = window.location.hash.slice(1)
if (this.$route.path !== currentPath) {
this.$router.push(currentPath)
}
}, false)
}
2、尝试用setTimeout来处理
缺点:虽然可以解决,但是setTimeout的合理值无法确定。还有一个问题就要是维护这个定时器,需要在点击之前先清除原有定时器,要不然执行会混乱。
this.$route.back();
setTimeout(() => {
this.$store.commit("error/reset");
}, 50)
3、利用H5提供的history的popstate事件来处理
window.addEventListener("popstate", function(e) {
}, false);
通过回调函数处理
$back(callback) {
if (NativeExternalRequest.back(callback)) {
return;
}
if (callback) {
EventUtil.on(window, 'popstate', (e) => {
EventUtil.off(window, 'popstate');
callback(e);
}, EventUtil.defineOptions({
capture: true,
}));
}
this.$router.back();
}