问题:
我在写移动端的时候碰见了一个问题,有一个页面可以点击下一条,这样就会无限的跳转路由,此时就需要忘记路由记录,返回的时候回到跳进当前页面的页面。
解决:
起初,我直接使用的vue的router的replace,但因此又出现了问题,使用this.$router.replace时,路由记录的确没了, 但在手机上使用手势导航返回,会出现无法返回,手势导航会根据replace跳转的次数,手势导航返回就要几次
因此 ,我监听了浏览器返回的事件,对返回事件触发时做处理就好了。
// 进入页面时保存当前页url
mounted() {
if (window.history && window.history.pushState) {
// 向历史记录中插入了当前页
console.log('向历史记录中插入了当前页')
history.pushState(null, null, document.URL)
window.addEventListener('popstate', this.goBack, false)
}
},
// 监听页面销毁
destroyed() {
console.log('离开当前页面')
window.removeEventListener('popstate', this.goBack, false)
},
methods: {
// 页面销毁时走这个方法
goBack() {
console.log('点击了浏览器的返回按钮')
// 清缓存
sessionStorage.clear()
window.history.back()
history.pushState(null, null, document.URL)
},
},
beforeRouteLeave(to, from, next) {
// 如果这个页面有跳转其他页面的路由,所以在组件的路由钩子里也需要清下缓存
sessionStorage.clear()
next()
},