js 关闭页面时弹框提醒

关闭页面时弹框提醒

在做vue项目时一个可编辑的详情页面需要在离开它的时候,根据页面是否改动的情况来判断是否要离开页面,一开始我只是在beforeRouteLeave里面调用的==window.confirm()==来提示,

//调用
  beforeRouteLeave (to, form, next) {
    
    
    const isNext = this.isCanNextRoute() //这个是布尔值,来判断是否需要提示;
    console.log('isNext:', isNext)		 // true:不需要; false:需要;
    if (isNext) {
    
    
      next()
    } else {
    
    
      const isConfirm = window.confirm('您当前页面数据还没保存,确认要离开吗?', {
    
    
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning',
        center: true
      })
      if (isConfirm) {
    
    
        next()
      }
    }
  },

这么做确实也简单,后面发现我理解错需求了,在关闭页面时也需要提示,于是去问了度娘得知了window.addEventListener(),需要搭配window.addEventListener()来注销它,第二个参数传的函数不能是匿名函数,这是我不小心踩得一个坑

  // 调用
  beforeRouteLeave (to, form, next) {
    
    
    const isNext = this.isCanNextRoute() //这个是布尔值,来判断是否需要提示;
    console.log('isNext:', isNext)		 // true:不需要; false:需要;
    if (isNext) {
    
    
      window.removeEventListener('beforeunload', this.demo, {
    
     passive: false })// 注销监听器
      next()
    } else {
    
    
      const isConfirm = window.confirm('您当前页面数据还没保存,确认要离开吗?', {
    
    
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning',
        center: true
      })
      if (isConfirm) {
    
    
        window.removeEventListener('beforeunload', this.demo, {
    
     passive: false }) // 注销监听器
        next()
      }
    }
  },
  created () {
    
    
    window.addEventListener('beforeunload', this.demo, false)
  },
  methods: {
    
    
        demo (e) {
    
    
	      const isNext = this.isCanNextRoute()
	      console.log('isNext:', isNext)
	      if (!isNext) {
    
    
	        e.returnValue = 'demo'
	        return 'demo'
	      } else {
    
      }
    },
  },
   destroyed () {
    
    
    window.removeEventListener('beforeunload', this.demo, {
    
     passive: false }) // 注销监听器
  }

用得比较浅,后面再看看

猜你喜欢

转载自blog.csdn.net/thesize/article/details/114819512