组件传值

事件总线:
就是创建一个事件中心,相当于中转站,可以用它来传递事件和接收事件

1.创建全局空Vue实例:eventBus

import Vue from 'vue';
const eventBus= new Vue()  //创建事件总线
export default eventBus;

2.具体页面使用$emit发布事件 - 传递值

import eventBus from '@u/eventBus'
eventBus.$emit('send',‘hello’)

3.具体页面使用$on订阅事件 - 接收组件值

import eventBus from '@u/eventBus'
eventBus.$on('send', msg => {
	console.log(msg)  //控制台输出 hello
}

注意:\(on先进行监听,一旦\)emit发布事件后所有组件都可以\(on监听到事件。所以传递参数的时候一定已经先进行了监听才能得到参数。比如在父组件中\)emit事件放在mounted钩子函数中,等待子组件创建并\(on开始监听事件后再去触发\)emit发布事件。

4.$off()移除事件监听

import eventBus from '@u/eventBus'
eventBus.$off('send')  

事件订阅功能\(on是\)eventBus对象完成的,与组件无关,如果用v-if销毁子组件的时候,会形成闭包,造成内存泄露,所有要在销毁组件的时候进行取消监听事件

posted on 2022-05-28 11:13  双月天  阅读(124)  评论(0编辑  收藏  举报

导航