vue_front__vue_front01_0">代码地址:https://github.com/kedaya-github/vue_front , vue_front01中
组件通信:
非父子组件之间
-
在components中定义一个公共的 bus.js文件,里面封装一个vue对象
// 创建一个Vue实例 import Vue from 'vue' export default new Vue()
-
components——>GG.vue : 两个没有关系的路由组件
<template> <div> 哥哥组件: <input type="button" value="发送信息到 MM" @click="sendMsg()"> </div> </template> <script> import bus from './bus.js'; //引入 bus.js , 使用bus向 MM 路由组件传值 export default { data() { return { ggMsg : "哥哥组件信息" } }, methods:{ sendMsg(){ bus.$emit("GGMM" , this.ggMsg , "测试多数据"); //调用bus.$emit() 绑定一个事件 , 第二个参数为 要传递的数据 } }, } </script>
-
components——>MM.vue : 接收 GG.vue 传递的数据
<template> <div> MM组件: GG组件的信息 : {{mmMsg}} </div> </template> <script> import bus from './bus.js'; export default { data() { return { mmMsg : "" } }, created(){ //初始化数据时,获取GG组件 传递的数据 bus.$on("GGMM" , (data,msg) => { //bus.$on 来获取非父子组件传递的数据 第一个参数为共同绑定的事件 , data为传递的数据, console.log(msg); //() 中可以传递多值 this.mmMsg = data; }) } } </script>