Vue 父子组件 监听scroll事件

3 篇文章 0 订阅

借助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 ==》实现吸顶的效果	
})

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue中,组件可以通过监听组件事件来获取组件的状态或者触发一些操作。具体实现方法如下: 1.在组件中定义一个事件,并在需要触发该事件的地方使用`$emit`方法触发该事件,例如: ```javascript // 组件中定义事件 this.$emit('child-event', 'hello from child component') ``` 2.在组件中使用`v-on`指令监听组件事件,并在回调函数中处理事件,例如: ```html <!-- 组件监听组件事件 --> <child-component v-on:child-event="handleChildEvent"></child-component> ``` ```javascript // 组件中处理组件事件 methods: { handleChildEvent(data) { console.log(data) // 输出:'hello from child component' } } ``` 另外,在Vue 2中,还可以使用`@hook`事件监听组件的生命周期事件,例如: ```html <!-- 组件监听组件生命周期事件 --> <child-component v-on:hook:mounted="handleMounted"></child-component> ``` ```javascript // 组件中处理组件生命周期事件 methods: { handleMounted() { console.log('child component mounted') } } ``` 在Vue 3中,可以使用类似上面的`@hook`事件监听组件的生命周期事件,例如: ```html <!-- 组件监听组件生命周期事件 --> <child-component v-on:hook:mounted="handleMounted"></child-component> ``` ```javascript // 组件中处理组件生命周期事件 methods: { handleMounted() { console.log('child component mounted') } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值