先放教程,再说原因
methods: {
jumpToOtherPage(cb) {
this.isJumpToOtherPage = true
cb();
},
data() {
return {
isJumpToOtherPage: false, // 是不是手动跳转到别的页面,如果是那么放行,如果不是,那么拦截
router 钩子:next->true 跳转,否则不跳
beforeRouteLeave(to, from, next) {
next(this.isJumpToOtherPage)
},
所有跳转,只要是本页面的跳转,都放行
this.jumpToOtherPage(()=> {
this.$router.replace({
name: 'career-advancement'
})
})
原因
网上搜的正常大家都会使用
addEventListener() {
window.history.pushState(null, null, document.URL);
// window.history.replaceState(null, null, document.URL);
window.removeEventListener('popstate', this.backPageEmit);
window.addEventListener('popstate', this.backPageEmit);
},
相关API
pushState
History API
在 HTML 文档中,history.pushState() 方法向当前浏览器会话的历史堆栈中添加一个状态(state)。
当vue 调用 this.$router.replace
时,replace的是 pushState 的历史页,所以浏览器点击返回,会回退到上一个页面,因为上一个页面没有被替换掉,router历史栈还存在。
我搜了下,history 有 History.replaceState()
和 History.go()
方法 ,但是需要添加额外的判断。亲自行斟酌。
上述方法有两个缺点:
- 需要所有跳转的地方都使用上述回调
- 需要子组件也使用该方法。所以子组件需要添加事件监听, 或者使用vuex