禁止浏览器返回键操作

625 阅读1分钟
  mounted () {
      // 禁用浏览器返回键
      history.pushState(null, null, document.URL);
      window.addEventListener('popstate', this.disableBrowserBack);
  },
  destroyed () {
    // 清除popstate事件 否则会影响到其他页面
      window.removeEventListener("popstate", this.disableBrowserBack, false);
  }
  methods //...
  disableBrowserBack() {
      history.pushState(null, null, document.URL);
      this.$confirm('此操作将退出此页面未保存内容, 是否继续退出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '成功退出!'
        });
        // 返回上一路由 实际是上二级浏览器记录
        this.$router.go(-2);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });          
      });
  }