判断浏览器页面关闭还是刷新

4,768 阅读1分钟

1,登录态本地信息判断/否则登录

 $route(){
  if(!localStorage.getItem("userName"))  {
    this.$router.push({ path: "/login" });
  }
},

2,监听关闭前的事件

  mounted() {
    // window.addEventListener("beforeunload", this.onbeforeunload);
    // window.addEventListener("unload", this.onunload);
  },

3,监听方法

  methods:{
     //在即将离开当前页面(刷新或关闭)时执行
     onbeforeunload() {
        this._beforeUnload_time = new Date().getTime();
     },
     //当用户未载入文档时执行
     onunload() {
       this._gap_time = new Date().getTime() - this._beforeUnload_time;
       if (this._gap_time <= 5) {
          //关闭浏览器,清除本地用户数据
         window.localStorage.clear()
       }
     }

  }