vue 阻止浏览器右上角返回以及安卓硬件返回(拦截页面返回)

开发场景:
在某些填写表单类型的页面要求有返回时要保存所填写内容的需求。

框架: vue2 + vant2

代码:

  mounted() {
    if (window.history && window.history.pushState) {
      if(window.history.length>1){
      const state = {
        key: Math.random() * new Date().getTime()
      }
      window.history.pushState(state, null, document.URL)
      }
       //给window添加一个监听事件popstate,拦截返回键,并执行方法 backFn
      window.addEventListener('popstate', this.backFn, false)
    }
  },
 methods:{
    backFn () {
    // 返回执行逻辑 此处还可以添加对话框
    const state = {
    key: Math.random() * new Date().getTime()
    }
    window.history.pushState(state, null, document.URL)

    this.$dialog.confirm({
      title: '温馨提示',
      message: '是否保存到草稿?',
      confirmButtonText: '保存',
      cancelButtonText:'不保存'
    })
      .then(() => {
      	//防止保存时用户填写错误,然后直接返回关闭页面
        window.history.pushState(state, null, document.URL)
       // 保存后的逻辑
      })
      .catch(() => {
        //不保存的逻辑
      })
    }
  }

最后要记得销毁监听事件

destroyed(){
		//销毁监听
		window.removeEventListener('popstate',this.backFn,false)
	}

只有state一直在变化,点击返回的时候才能触发popstate

popstate事件不适合作为公共方法,需要每个页面去设置赋值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值