当前位置: 首页 > news >正文

【Vue】学习笔记-全局事件总线

全局事件总线(GlobalEventBus)

一种可以在任意组件通信的方式,本质上就是一个对象,它必须满足以下条件

  1. 所有的组件对象都必须能看见他
  2. 这个对象必须能够使用$ on $ emit $ off方法取绑定、触发和解绑事件

使用步骤

  1. 定义全局事件总线
//创建VUE
new Vue({el:'#app',render:h=> h(App),beforeCreate(){Vue.prototype.$bus=this //安装全局事件总线},})
  1. 使用事件总线
    a.接收数据:A组件想接收数据,则在A组件中给$bus 绑定自定义事件,事件的回调留在A组件自身
export default{methods(){demo(data){...}}...mounted(){this.$bus.$on('xxx',this.demo)}
}

b.提供数据:this.$bus.$emit(''xxx,data)
3. 最好在beforeDestroy钩子中,用**$off()**去解绑当前组件所用到的事件。

src/main.js

//引入vue
import Vue from 'vue'
//引入APP.vue
import App from './App.vue'//关闭Vue的生产提示
Vue.config.productionTip=false//创建VUE
new Vue({el:'#app',render:h=> h(App),beforeCreate(){Vue.prototype.$bus=this //安装全局事件总线},})

src/App.vue

<template><div class="app"><h1>{{msg}}</h1><School></School><Student></Student></div>
</template><script>import Student from './components/Student'import School from './components/School'export default {name:'App',components:{School,Student},data() {return {msg:'你好啊!'}}}
</script><style scoped>.app{background-color: gray;padding: 5px;}
</style>

src/compoents/School.vue

<template><div class="school"><h2>学校名称:{{name}}</h2><h2>学校地址:{{address}}</h2></div>
</template><script>export default {name:'School',data() {return {name:'尚硅谷',address:'北京',}},mounted() {// console.log('School',this)this.$bus.$on('hello',(data)=>{console.log('我是School组件,收到了数据',data)})},beforeDestroy() {this.$bus.$off('hello')},}
</script><style scoped>.school{background-color: skyblue;padding: 5px;}
</style>

src/compoents/Student.vue

<template><div class="student"><h2>学生姓名:{{name}}</h2><h2>学生性别:{{sex}}</h2><button @click="sendStudentName">把学生名给School组件</button></div>
</template><script>export default {name:'Student',data() {return {name:'张三',sex:'男'}},mounted() {// console.log('Student',this.x)},methods: {sendStudentName(){this.$bus.$emit('hello',this.name)}},}
</script><style  scoped>.student{background-color: pink;padding: 5px;margin-top: 30px;}
</style>

在这里插入图片描述

http://www.lryc.cn/news/67633.html

相关文章:

  • MATLAB数值运算(六)
  • 某医院Pad网络故障分析
  • git 撤销中间某次提交,保留其他提交的方法
  • 空中下载技术(OTA)电控信息安全
  • 数据库sql语句(count(*)和count(字段))
  • 短视频矩阵源码系统
  • 检测数据类型
  • 【2023春招】4399 web后台-Java后端开发
  • 干货分享:PCB防静电设计的必要性
  • 电脑压缩包文件不见了怎么办?2种办法轻松找回电脑丢失文件!
  • 如何申请gpt4.0-如何接入ChatGPT4
  • 设计模式-备忘录模式
  • 阿里、京东等大厂年薪50w的测试都是什么水平?
  • Java PECS(Producer Extends Consumer Super)原则
  • Learn RabbitMQ with SpringBoot
  • 定时器 POSIX Timer定时器和setitimer定时器
  • DeSD:用于3D医学图像分割的深度自蒸馏自监督学习
  • MySQL数据库——MySQL创建触发器(CREATE TRIGGER)
  • Java实现网上人才招聘系统【附源码】
  • jmeter接口测试项目实战详解,零基础也能学,源码框架都给你
  • MySQL中去重 distinct 和 group by 是如何去重的
  • 在职读研是理想还是情怀?你想要的都将在社科大能源管理硕士项目实现
  • 携手共建数字钢铁,Hightopo亮相第三届钢铁展洽会
  • Leetcode2383. 赢得比赛需要的最少训练时长
  • js代码执行过程、调用栈、执行上下文
  • 互联网摸鱼日报(2023-05-12)
  • 【Python从入门到实践3.1】扑克发牌知识点(range函数,def函数,else语句配合使用,random库,列表推导式)
  • Spring Cloud第二季--Spring Cloud Bus
  • Unittest自动化测试之unittestunittest_生成测试报告
  • 一个查询IP地理信息和CDN提供商的离线终端工具