SoFunction
Updated on 2025-04-10

How to listen for scrolling events by vue

Listen to scroll events in vue and then handle them. Generally, there are: 1. Scroll to the top to adsorb; 2. Activate the corresponding tab key (anchor link tab key) according to the scroll position (anchor link tab key)

Both methods of processing can be achieved by listening to scroll

mounted(){
('scroll',) // Listen to the scroll event, and then use the handleScroll method to handle it accordingly}

How to deal with it

1. Scroll to top to absorb

html element

<!--ifisFixedfortrueWord,Just addclass is_fixed Set fixed positioning-->
<div  :class="{'is_fixed' : isFixed}">
This is the element to be rolled to the top to absorb
</div>

methods methods

handleScroll(){
let scrollTop =  ||  ||  // Scrollbar offsetlet offsetTop = ('#boxFixed').offsetTop; // Offset of the element to be scrolled to the top = scrollTop > offsetTop ? true : false; // If scrolling to the top, it is true}

2. Activate the corresponding tab key according to the scrolling position (anchor link tab key)

Implement anchor links in vue. You cannot use the a link directly, because you use hash routes. Direct a link will jump to the route. You can use scrollIntoView for details./zh-CN/docs/Web/API/Element/scrollIntoView

(1) Implement anchor links:

<div class="flexitem" v-for="(item,index) in tabs" :class="seeThis==index?'active':''"><a href="javascript:void(0)" rel="external nofollow" @click="goAnchor(index)">{{item}}</a></div>

<div >block1</div>

(2) Implement scrolling to the corresponding position to activate the tab

data(){
return{
seeThis:0,
tabs:['tab0','tab1','tab2'],
}
},
methods:{
goAnchor(index) { // You can also use the scrollIntoView method, but since the head is fixedly positioned here, this method is used// ('#anchor'+index).scrollIntoView()
 = index; var anchor = this.$('#anchor'+index)
 = -100
 = -100
},
}
methods:{
handleScroll(){
var anchorOffset0 = this.$('#anchor0').offsetTop-100
var anchorOffset1 = this.$('#anchor1').offsetTop-100
var anchorOffset2 = this.$('#anchor2').offsetTop-100
if(scrollTop>anchorOffset0&&scrollTop<anchorOffset1){
 = 0
}
if(scrollTop>anchorOffset1&&scrollTop<anchorOffset2){
 = 1
}
if(scrollTop>anchorOffset2){
 = 2
}
},
}

The above is the detailed content of the method of Vue listening to scroll events. For more information about Vue listening to scroll events, please follow my other related articles!