使用事件总线(eventbus)或自定义事件的问题

本文探讨了Vue组件间的通信方法,通过事件总线和自定义事件的关键点,强调了监听事件时机的选择以及组件生命周期顺序。同时介绍了如何在A组件beforeCreate阶段监听事件,在B组件beforeDestroy阶段触发事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

事件总线、自定义事件关键点

  • 先监听事件再触发事件
  • 考虑组件生命周期顺序

组件通信

<!-- 组件A -->
<template>
  <div>
    <button @click="jump">跳转B</button>
    {{msg}}
  </div>
</template>

<!-- 组件B -->
<template>
  <div>
    <button @click="back">返回</button>
  </div>
</template>
// A
jump () {
  this.$router.push('/b')
}

// B
back () {
	this.$router.go(-1)
}
自定义事件
// A
getData (e) {
    this.msg = e.detail.msg
}

beforeCreate () {
	window.addEventListener('cancel', this.getData)
}

destoryed () {
	window.removeEventListener('cancel', this.getData)
}
// B
dispatchEvent () {
	const cancelEvent = new CustomEvent('cancel', {
		detail: {
			msg: '结果'
        }
    })
    window.dispatchEvent(cancelEvent)
    console.log('触发')
}

beforeDestroy () {
	this.dispatchEvent()
}
事件总线
// main.js
window.eventBus = new Vue()
// A
beforeCreate () {
	eventBus.$off('cancel')
	eventBus.$on('cancel', data => {
		this.msg = data
	})
}
// B
beforeDestroy () {
	eventBus.$emit('cancel', {msg: '结果'})
}
  • 生命周期触发顺序
    在这里插入图片描述

要保证监听事件在触发事件之前

A中监听事件可写在 beforeCreate created beforeMount
B中触发事件可写在 beforeDestory destoryed

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值