前言
需求: 当用户关闭浏览器或者标签页的时候,自动退出系统
beforeunload_event: https://developer.mozilla.org/zh-CN/docs/Web/API/Window/beforeunload_event
unload_event: https://developer.mozilla.org/zh-CN/docs/Web/API/Window/unload_event
内容
<template> <div id="app"> <transition mode="out-in" enter-active-class="fadeInDownBig" leave-active-class="fadeOutUpBig" > <router-view class="animated" /> </transition> </div> </template> <script> import { mapActions } from "vuex"; export default { name: "App", data() { return { beforeunloadTime: 0, unloadTime: 0 }; }, mounted() { window.addEventListener('beforeunload', e => this.beforeunloadHandler(e)); window.addEventListener('unload', e => this.unload(e)); }, destroyed() { window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e)); window.removeEventListener('unload', e => this.unload(e)); }, methods: { ...mapActions(["logout"]), beforeunloadHandler() { this.beforeunloadTime = new Date().getTime() }, unload() { this.unloadTime = new Date().getTime() // window.localStorage.setItem('timer', String(this.unloadTime - this.beforeunloadTime)) // 本地通过localStorage中的数据看出,关闭事件间隔小于1,刷新则大于8 if (this.unloadTime - this.beforeunloadTime <= 1) { // 执行退出登录 this.logout(true) } } } }; </script>
学无止境,谦卑而行.