vue 监听浏览器关闭或刷新事件
需求
web项目中使用socket时,涉及到关闭刷新浏览器多次连接问题,其中一个解决方法是在关闭或刷新浏览器时,将连接断开。
代码
<script>
export default {// 可以在created、beforeMount或mounted生命周期,其中一个添加created() {window.addEventListener('beforeunload', this.onBeforeunload)// 关闭窗口调用事件},methods: {onBeforeunload(e) {// 这里是你要执行的方法 比如关闭连接,清除缓存,保存数据等待....},}// 只能卸载beforeDestroy中,不能写在destroyed中beforeDestroy() {// 关闭刷新浏览器销毁监听window.removeEventListener('beforeunload', this.onBeforeunload) // 关闭窗口销毁},
}</script>