Detailed explanation of scroll bar position and scroll monitoring events when using vue router for page switching

  • 2021-08-03 08:25:26
  • OfStack

According to normal product logic, the scroll bar should be at the top of the page when we switch pages, but. . . When using vue-router to switch pages, I found that the position of scroll bar was automatically recorded, and the scroll monitoring event defined in another component would still run, which really surprised me. . .

Tell me about my cracking method:

1. In the mounted hook of each component that needs to be switched by vue-router, the position of the page is automatically rolled back to the top of the page to solve the problem of automatic recording of scroll bar position;

2. Define a variable scrollWatch as true by default in each component, add an if judgment when binding rolling monitoring events, only monitor functions when scrollWatch is true, and then set variable scrollWatch as false in the hook of component destroyed; This solves the problem that scrolling listening will still run in other components.


<script>
import $ from 'jquery';
export default {
 data () {
 return {
  scrollWatch: true
 }
 },
 mounted() {
 $(window).scrollTop(0);
 $(window).on('scroll', () => {
  if (this.scrollWatch) {
   //your code here
  }
  }
 });
 },
 destroyed () {
 this.scrollWatch = false;
 }
}
</script>

Related articles: