网络编程
位置:首页>> 网络编程>> JavaScript>> Vue全局事件总线你了解吗

Vue全局事件总线你了解吗

作者:richest_qi  发布时间:2024-04-28 09:25:11 

标签:Vue,全局,事件,总线

全局事件总线,是组件间的一种通信方式,适用于任何组件间通信。

看下面具体的例子。

父组件:App

<template>
   <div class="app">
       <Company/>
       <Employee/>
   </div>
</template>

<script>
import Company from "./components/Company.vue";
import Employee from "./components/Employee.vue";

export default {
   components:{
       Company,
       Employee
   }
}
</script>

<style>
.app{
   background: gray;
   padding: 5px;
}
.btn{
   margin-left:10px;
   line-height: 30px;
   background: ivory;
   border-radius: 5px;
}
</style>

子组件:Company和Employee

<template>
 <div class="company">
     <h2>公司名称:{{name}}</h2>
     <h2>公司地址:{{address}}</h2>
     <button @click="sendMessage">点我发送</button>
 </div>
</template>

<script>
export default {
   name:"Company",
   data(){
       return {
           name:"五哈技术有限公司",
           address:"上海宝山"
       }
   },
   methods:{
       sendMessage(){
           console.log("Company组件发送数据:",this.name);
           this.$bus.$emit("demo",this.name);
       }
   }

}    
</script>

<style scoped>
.company{
   background: orange;
   background-clip: content-box;
   padding: 10px;
}
</style>
<template>
 <div class="employee">
     <h2>员工姓名:{{name}}</h2>
     <h2>员工年龄:{{age}}</h2>
 </div>
</template>

<script>
export default {
   name:"Employee",
   data(){
       return {
           name:"张三",
           age:25
       }
   },
   mounted(){
       this.$bus.$on("demo",(data) => {
           console.log("Employee组件监听demo,接收数据:",data);
       })
   },
   beforeDestroy() {
       this.$bus.$off("demo");
   }
}

</script>

<style scoped>
.employee{
   background: skyblue;
   background-clip: content-box;
   padding: 10px;
}
</style>

入口文件:main.js

import Vue from 'vue';  
import App from './App.vue';

Vue.config.productionTip = false;

new Vue({
 el:"#app",
 render: h => h(App),
 beforeCreate(){
   Vue.prototype.$bus = this;
 }
})

父组件App,子组件CompanyEmployee

子组件Company和Employee之间通过全局数据总线进行数据传递。

在main.js中,定义了全局事件总线:$bus

$bus定义在Vue.prototype,因此$bus对所有组件可见,即所有组件可通过this.$bus访问。

$bus被赋值为this,即vm实例,因此$bus拥有vm实例上的所有属性和方法,如$emit$on$off等。

new Vue({
 beforeCreate(){
   Vue.prototype.$bus = this;
 }
})

使用全局事件总线

$bus.$on,监听事件。Employee组件中定义了监听事件,监听demo事件;

$bus.$emit,触发事件。Company组件中定义了触发事件,点击按钮执行sendMessage回调,该回调将触发demo事件。

Vue全局事件总线你了解吗

Vue全局事件总线你了解吗

来源:https://blog.csdn.net/qzw752890913/article/details/123057294

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com