最近用vue开发的一个app,发现一个奇怪的问题,点击头部返回键调用了router.go(-1),结果没有返回上一级页面,用router.push()跳转到下一级页面又是可以的,debugger调试发现确实触发到了router.go(-1)事件,最开始是在安卓手机偶尔出现这种情况,一开始以为是安卓系统的问题,后来发现在苹果手机也会出现,那这就应该是vue-router的问题,百度一圈没看到解决方法,困扰了我一段时间,后来才找到答案 看这里
两种解决方法:
1、将路由模式改为History模式
2、hash模式中使用h5新增的onhashchange事件做hack处理
mounted () {
// 检测浏览器路由改变页面不刷新问题,hash模式的工作原理是hashchange事件
window.addEventListener('hashchange', () => {
let currentPath = window.location.hash.slice(1)
if (this.$route.path !== currentPath) {
this.$router.push(currentPath)
}
}, false)
},
重新刷新一遍路由,问题就可以解决啦!