Project scenario:
Click the button to open a page in a new window Switch pages can trigger a function every time to get the latest data, do not want to manually refresh
Solution 1:
mounted(){
// The method used to listen to the visibilitychange event of the document object. This event is fired when the user opens or minimizes the current page, or switches browser tabs.
document.addEventListener('visibilitychange', this.monitor)
},
methods:{
monitor(e) {
let isExist = e.target.visibilityState
console.log(isExist)
if (isExist === 'visible') {
console.log(new Date().toLocaleString(), `You have entered the page!`)
} else {
// Toggle or close will trigger
// alert(new Date().toLocaleString(), `You have left the page!`)
}
}
}
Solution 2:
mounted(){
window.onfocus = ()=> {
// Execute this function when the page is focused
// console.log('Every time you switch back to this page, the function `getgenntDate()` will be executed once.');
this.getgenntDate();
}
};
Solution 1 can only monitor the entry and exit of a certain page
Scenario 2 Triggering any page will trigger an event in the browser that is equivalent to