Vue学习笔记3--全局事件总线

18 篇文章 0 订阅

Vue学习笔记3—全局事件总线

1.全局事件总线可以实现任意组件间通信

全局事件总线示意图

X需具备的条件:

  • 所有的组件都要能看见X
  • 可以调用$on $off $emit
  • Vue.prototype.x ={a:1, b:2} 可以被所有组件看见
  • VueComponent.protoype.proto === Vue.prototype
  • 组件实例对象(vc)可以访问到Vue原型上的属性、方法

在这里插入图片描述

2. 安装全局事件总线(main.js)

//创建vm
new Vue({
	el:'#app',
	render: h => h(App),
	beforeCreate() {
		Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
	},
})

3.使用事件总线

  • 接收数据: A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。
methods(){
  demo(data){......}
}
......
mounted() {
	this.$bus.$on('hello',this.demo)//绑定自定义事件
},


  • B组件触发自定义事件,并提供数据,
this.$bus.$emit('hello',data)
  • 最好在A组件的beforeDestroy钩子中,用$off去解绑当前组件所用到的事件,已防止$bus负担过重
beforeDestroy(){
	this.$bus.$off('hello')
}
  • 20
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
vue3-seamless-scroll是一个基于Vue3的无缝滚动组件库,可以用于创建无限滚动、轮播等效果的滚动视图。如果您想监听vue3-seamless-scroll的滚动事件,可以通过以下步骤实现: 1. 在组件中引入vue3-seamless-scroll,并添加需要滚动的内容和相关配置: ```html <template> <div class="scroll"> <vue3-seamless-scroll :options="options"> <ul> <li v-for="(item, index) in list" :key="index">{{ item }}</li> </ul> </vue3-seamless-scroll> </div> </template> <script> import Vue3SeamlessScroll from 'vue3-seamless-scroll' export default { components: { Vue3SeamlessScroll }, data() { return { list: ['item1', 'item2', 'item3'], options: { step: 1, limitMoveNum: 1, direction: 'horizontal' } } } } </script> ``` 2. 在组件中使用ref来获取vue3-seamless-scroll组件的实例,并在mounted生命周期中注册滚动事件监听器: ```html <template> <div class="scroll"> <vue3-seamless-scroll ref="scroll" :options="options"> <ul> <li v-for="(item, index) in list" :key="index">{{ item }}</li> </ul> </vue3-seamless-scroll> </div> </template> <script> import Vue3SeamlessScroll from 'vue3-seamless-scroll' export default { components: { Vue3SeamlessScroll }, data() { return { list: ['item1', 'item2', 'item3'], options: { step: 1, limitMoveNum: 1, direction: 'horizontal' } } }, mounted() { const scroll = this.$refs.scroll.$refs.scroll scroll.addEventListener('scroll', this.handleScroll) }, methods: { handleScroll() { console.log('scrolling...') } } } </script> ``` 在上述代码中,我们使用$refs来获取vue3-seamless-scroll组件的实例,并使用addEventListener方法在mounted生命周期中注册了滚动事件监听器handleScroll。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值