目录

onbeforeunload

beforeRouteLeave


onbeforeunload

浏览器自带的onbeforeunload事件可以用在页面刷新前,页面关闭前,进行提示判断等相关操作。也就是说当你在点击f5刷新、点击刷新按钮或者关闭这个页面都会触发这个事件。

 这里我做了一个判断,当我的路由的name是Tree的时候才会在离开页面的时候触发这个事件,其余页面均不会触发这个事件。

写在APP.vue或者所需页面中都可

mounted () {
    var that = this
    window.onbeforeunload = function (e) {
      if (that.$route.name === 'Tree') {
        var message = 'some word';
        e = e || window.event;
        if (e) {
          e.returnValue = message;
        }
        return "浏览器关闭!";
      } else {
        window.onbeforeunload = null;
      }
    }
  },
beforeDestory () {
  window.onbeforeunload = null
},

注意:

1、上面的方法生效的前题是,打开该网页后,需要鼠标点击一下网页,让网页获取焦点,然后再关闭或刷新! 若打开后不点击页面直接关闭或刷新不会触发该方法。

2、必须写return

beforeRouteLeave

 beforeRouteLeave(to,from,next)表示离开路由之前执行的函数,可用于页面的反向传值,页面跳转。

<template>
  <div>表单</div>
</template>
 
<script>
 
export default {
  beforeRouteLeave (to, from, next) {
 
    //跳转路由前进行一些操作
    。。。。
 
 
    this.$confirm('有未保存的数据,是否保存数据?', '提示', {
      confirmButtonText: '保存',
      cancelButtonText: '不保存',
      type: 'warning'
    }).then(data => {
      console.log('保存的操作');
    }).catch(err => {
      console.log('不保存的操作');
      next()//放行
    })
  }
}
</script>
 

注意:当页面有返回按钮时,不要用this.$router.go(-1),不然会出现confirm闪出来一下又消失掉

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐