vue 事件$on,$off的注意事项

遇到的vue事件on,off的坑

组件 A 使用了 组件B

组件A产生事件:

TypeScript 复制代码
this.$root.$emit('event1', param)

组件B的created()里监听了事件:

TypeScript 复制代码
this.$root.$on('event1', (param)=>{...})

组件B的beforeDestroy()里取消了事件监听:

TypeScript 复制代码
this.$root.$off('event1')

组件刷新时出现了:组件B2 created() ->组件B1 beforeDestroy() 导致组件B2里的监听被清除了

修改方案:

组件B的created()里监听事件,留下函数句柄

TypeScript 复制代码
this.event1Callback = (param)=>{...}
this.$root.$on('event1', this.event1Callback)

组件B的beforeDestroy()里使用函数句柄取消事件监听:

TypeScript 复制代码
this.$root.$off('event1', this.event1Callback)
相关推荐
IT_陈寒4 分钟前
Vue的响应式让我熬到凌晨三点,原来漏了这个小细节
前端·人工智能·后端
一 乐7 分钟前
二手交易平台|基于springboot + vue二手交易平台(源码+数据库+文档)
java·数据库·vue.js·spring boot·小程序
Blanche150014 分钟前
利用 RAG 为答疑机器人扩展知识范围
前端
天若有情67320 分钟前
【纯前端小工具】公历生日转农历,批量查询每年农历生日对应的公历日期(GitHub Pages在线直接用)
前端·javascript·github pages·农历转换·lunisolar·网页小工具
SoonITer21 分钟前
怎样构建一个 Agent-friendly 的网站
前端·agent
颜进强37 分钟前
01 · NestJS 是什么:用途、解决什么问题、与热门框架对比
前端·后端·ai编程
wendZzoo40 分钟前
前端工程师的 3D 第一课:一个模型如何进入网页
前端
颜进强1 小时前
04 · NestJS 依赖注入:你在 `@Module` 写的 providers,和构造参数里那个类型,是怎么"对上"的?
前端·后端·ai编程
vx-程序开发1 小时前
【计算机毕设】django校园跑腿服务系统83141
java·数据库·vue.js·spring boot·spring·elasticsearch·django
肆仲冬1 小时前
不用框架,用 TypeScript 从零搭一个 Agent 框架
前端