1、代码(App.vue)
<script>
export default {
name: 'App',
mounted() {
document.addEventListener("visibilitychange", e=>{
if(document.visibilityState === "hidden"){
this.handleFn()
}
})
window.addEventListener('beforeunload', e => this.handleFn())
},
destroyed() {
document.removeEventListener("visibilitychange", e=>{
if(document.visibilityState === "hidden"){
this.handleFn()
}
})
window.removeEventListener('beforeunload', e => this.handleFn())
},
methods:{
handleFn(){
const URL = process.env.VUE_APP_BASE_API+"/uploads/deleteAll"
navigator.sendBeacon(URL)
}
}
}
2、参考文章
- Vue监听浏览器刷新
- 监听浏览器页面切换/刷新/关闭事件
- MDN Web Docs