zoukankan      html  css  js  c++  java
  • vue项目中阻止浏览器左侧返回键

    某些页面弹出提示框的时候,点击返回键后隐藏提示框,而不是返回到上一个页面。

    mounted() {
      //页面一进来的时候,就添加一个历史记录
      window.history.pushState(null, null, document.URL);
      // 给window添加一个popstate事件,拦截返回键,执行this.onBrowserBack事件,addEventListener需要指向一个方法
      window.addEventListener("popstate", this.onBrowserBack, false);
    },
    watch: {
      // 弹框监听,当弹框显示的时候,pushState添加一个历史,供返回键使用
      PopupShow: {
        handler(newVal, oldVal) {
          if (newVal.Terms === true) {
            window.history.pushState(null, null, document.URL);
          }
        },
        deep: true
      }
    },
     onBrowserBack() {
          // 比如判断需求执行back()或者go(-2)或者PopupShow=false隐藏弹框
          if (this.isEdit && this.addDialogVisible) {
              this.$confirm('当前有没有要编辑的内容,确定返回列表,将放弃本次操作', '提示', {
                   confirmButtonText: '确定',
                   cancelButtonText: '取消',
                   type: 'warning'
              }).then(() => {
                   if (this.isEdit && this.addDialogVisible) {
                       this.addDialogVisible = false
                   }
                   this.$router.go(-1)
               }).catch(() => {
                   window.history.pushState(null, null, document.URL);
                   console.log('1')
               });
           } else if (this.addDialogVisible2) {
               this.$confirm('当前有没有要编辑的内容,确定返回列表,将放弃本次操作', '提示', {
                   confirmButtonText: '确定',
                   cancelButtonText: '取消',
                   type: 'warning'
               }).then(() => {
                   if (this.addDialogVisible2) {
                       this.$refs.contrast.delmodifysiteFns()
                       this.addDialogVisible = false
                   }
                   this.$router.go(-1)
               }).catch(() => {
                   window.history.pushState(null, null, document.URL);
               });
           } else {
               this.$router.go(-1)
           }
       }
    destroyed() {
      // 当页面销毁必须要移除这个事件,vue不刷新页面,不移除会重复执行这个事件
      window.removeEventListener("popstate", this.onBrowserBack, false);
    }
  • 相关阅读:
    vue教程1-07 模板和过滤器
    vue教程1-06 v-bind属性、class和style
    vue教程1-05 事件 简写、事件对象、冒泡、默认行为、键盘事件
    Webstorm使用教程详解
    diff, cmp, patch
    grep, sed, awk
    which,whereis, locate, find
    tar, rar, unrar, zip, unzip
    groups, usermod, chown, chgrp, chmod
    pwd, cd, ls, touch, mkdir, rmdir, rm
  • 原文地址:https://www.cnblogs.com/theblogs/p/13067705.html
Copyright © 2011-2022 走看看