借助ref实现dom操作,借助eventHub实现消息传递
1. 监听scroll事件
如果 父子组件 嵌套 在父组件上 存在滚动
前提:父容器设置:overflow-y:scroll,子组件、孙子组件等未设置 则需在父组件上监听滚动事件有效,在子组件、孙子组件中监听无效, 在父组件 设置一个 ref="viewhome"; 在父组件的 mounted中设置: this.boxHome = this.$refs.viewhome this.boxHome.addEventListener('scroll',()=>{ let scTop = this.$refs.viewhome.scrollTop; this.$root.eventHub.$emit('getScrollValue',scTop); }) // 使用 this.$root.eventHub.$emit 实时传递数据
注意使用: $root.eventHub传递数据 设置:data部分 new Vue({ //常规设置:如i18n,router等 ...... ...... data: { eventHub:new Vue() } }).$mount('#app')子组建中建立接收消息机制:
在 子组件 或 孙子组件 添加: this.$root.eventHub.$on('scroll',(param)=>{ //param 接收父组件传递过来的值 //scroll的值 为滚动的距离,判断滚动的距离,添加相应的class ==》实现吸顶的效果 })