Vue parent and child components listen to scroll events

Realize dom operation with ref, realize message passing with

eventHub


Premise: Parent container setting: overflow-y:scroll, if child components, grandchild components, etc. are not set, it is necessary to monitor scroll events on the parent component to be valid, but it is invalid to monitor the child components and grandchild components.
Set a ref="viewhome" in the parent component;
Set in the mounted of the parent component:
this.boxHome = this.$refs.viewhome
this.boxHome.addEventListener('scroll',()=>{
let scTop = this.$refs.viewhome.scrollTop;    this.$root.eventHub.$emit('getScrollValue',scTop);
}) // use this.$root.eventHub.$emit to pass data in real time
Note the use of:
$root.eventHub pass data settings: data section
new View({
	//General settings: such as i18n, router, etc.
	......
	......
	data: {
		eventHub:new Vue()
	}
}).$mount('#app')
Create a message receiving mechanism in the sub-component:
In a child or grandchild add:
this.$root.eventHub.$on('scroll',(param)=>{
	//param receives the value passed by the parent component
	//The value of scroll is the scrolling distance, judge the scrolling distance, and add the corresponding class ==" to achieve the effect of ceiling suction	
})

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325284607&siteId=291194637