<!-- 组件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