创建一个新的Vue实例,以后它就承担起了组件之间通信的桥梁了,也就是中央事件总线。
1.新建一个文件夹用来容纳中央事件总线这个vue实例
// 中央事件总线就是新建一个vue实例用来当兄弟组件的数据桥梁 import Vue from "vue" export default new Vue()
2 兄弟传值 demoa需要把数据给demob
(1)现在demoa中使用$emit()把数据通过自定义事件绑定到那个vue实例上\
<template> <div> 组件a <button @click="fun()">点我把数据传递给我兄弟demob</button> </div> </template> <script> // 1.引用中央时间总线 import eventbus from "@/eventbus" export default { data(){ return { text:"我是demoa里面的变量" } }, methods:{ fun(){ // 2.在事件中直接给引进来的中央时间总线绑定自定义事件 eventbus.$emit("apao",this.text) } } } </script> <style> </style>
(2)在demob中使用$on来监听接收实例上的自定义事件
<template> <div> 组件b </div> </template> <script> // 1.引用中央时间总线 import eventbus from "@/eventbus" export default { // 2.来开始监听 mounted(){ eventbus.$on("apao",(val)=>{ console.log(val) }) } } </script> <style> </style>
1、创建一个事件总线,例如demo中的eventBus,用它作为通信桥梁 2、在需要传值的组件中用bus.$emit触发一个自定义事件,并传递参数(emit前加美元符) 3、在需要接收数据的组件中用bus.$on监听自定义事件,并在回调函数中处理传递过来的参数