Specific steps for vue browser to return to listening

  • 2021-10-27 06:10:28
  • OfStack

Preface

When sharing the page, I hope to click the browser back button to return to the home page of the project and increase the number of visits.

You need to listen for the browser's back button and block its default events.

The specific steps are as follows:

1. After mounting, judge whether the browser supports popstate


mounted(){
 if (window.history && window.history.pushState) {
 history.pushState(null, null, document.URL);
 window.addEventListener('popstate', this.goBack, false);
 }
},

2. Cancel listening when the page is destroyed. Otherwise, other vue routing pages will also be monitored


destroyed(){
 window.removeEventListener('popstate', this.goBack, false);
},

3. Write the monitoring operation in methods, and the cancellation of monitoring content in removeEventListener must keep 1 with the opening of monitoring, so the function is written in methods


methods:{
 goBack(){
 this.$router.replace({path: '/'});
 //replace Replace the original route to avoid a fallback loop 
 }
}

Attachment: What is popstate used for?

How to use popstate?

The new API of HTML5 extends window. history to make history points more open. The current history point pushState can be stored, the current history point replaceState can be replaced, and the history point popstate can be monitored.

pushState and replaceState are similar in usage.

Usage:


history.pushState(data,title,url);
// Among them 1 Parameters data It's for state The value of; No. 1 2 Parameters title Is the title of the page, but all browsers ignore this parameter at present, just pass an empty string; No. 1 3 Parameters url Is the link you want to go to; 

replaceState is used similarly, for example: history.replaceState("首页","",location.href+ "#news");

Summarize


Related articles: