Vue组件间通信实现原理和方式(父子组件、兄弟组件)


前言

本篇文章在上篇文章——Vue组件嵌套的理解与mixin的使用的基础上进行


包括父==>子传值 子==>父传值 兄弟组件传值

一、确立组件结构

1.在App中管理着两个兄弟组件student和school
如图:
在这里插入图片描述

二、通信方式

1.父组件给子组件传值

①.在父组件App.vue中对子组件student标签进行编写,代码如下:

<student name2="李四" :age2="18" />

②.student组件通过props对象接收:

//绑定方法:
 <button @click="get_AppInfo">获取父组件传来的值</button>
//加入props配置项:
  props: {
    
    
    name2: {
    
    
      type: String,
      required: true,
    },
    age2: {
    
    
      type: Number,
      required: true,
    },
  }
  //methods:
    get_AppInfo() {
    
    
            console.log("从父组件传来:", this.name2, this.age2);
    }

③.结果:
在这里插入图片描述

2.子组件给父组件传值

1. $ref方式

①.在父组件App.vue中对子组件school标签进行编写,代码如下:

<school ref="xuexiao" />
//在mounted钩子中加入
 this.$refs.xuexiao.$on("SoF", (data) => {
    
    
      console.log("我是App容器,收到来自子组件的信息:", data);
    });

②.student组件通过this.$emit触发对象接收:

//绑定方法:
  <button @click="send_AppInfo">发送信息给父组件</button>
  //methods:
       send_AppInfo(name) {
    
    
      this.$emit("SoF", this.name);
    },

③.结果:
在这里插入图片描述

2. v-on绑定事件方式

①.在父组件App.vue中对子组件school标签进行编写,代码如下:

//对school组件标签改为:
<school v-on:SoF2="getXuexiaoInfo" />
//在methods中加入
 getXuexiaoInfo(area) {
    
    
      this.msg = area;
      console.log("我是App容器,收到来自school组件的信息:", area);  }

②.school组件通过this.$emit触发对象接收:

//绑定方法(v-on方式):
  <button @click="send_AppInfo2">发送地区给父组件</button>
  //methods:
   send_AppInfo2(area){
    
    
      this.$emit("SoF2", this.area);
    },

③.结果:点击v-on按钮:
在这里插入图片描述

3.兄弟组件间传值

1. 全局事件总线$bus

①.在mainjs绑定全局事件总线$bus

new Vue({
    
    
  components: {
    
    
    school,
  },
  render: (h) => h(App),
  beforeCreate() {
    
    
    // 构造一个傀儡$bus来实现兄弟组件通信
    // 安装全局事件总线
    Vue.prototype.$bus = this;
  },
}).$mount("#app");

②.设置school向student组件发送信息。school组件代码:

//绑定方法:
<button @click="send_SchoolInfo">school组件发送信息到student组件</button>
  //methods:
      send_SchoolInfo(age) {
    
    
      this.$bus.$emit("bro", this.name);
    },

③.student组件设置对象接收:

//在mounted钩子中加入
    this.$bus.$on('bro',(data)=>{
    
    
      console.log("收到来自兄弟组件school的信息:",data)
    })

③.结果:
在这里插入图片描述


总结

可通过全局事件总线来实现所有组件间的通信。但是需要注意在使用之后解绑事件,即销毁组件之前解绑。

猜你喜欢

转载自blog.csdn.net/CherishTaoTao/article/details/125264105