Vue.js中全局事件总线的理解---尚硅谷笔记

Vue.js中全局事件总线的理解—尚硅谷笔记

全局事件总线:它就相当于是一个行驶在一个道路上的公共汽车,Vue就是那个道路,路的起始位置是学生,路的终点是学校。
学生拿着作业(StudentForHomeWork())乘着汽车到学校。
在这里插入图片描述

1: 创建一个事件总线(汽车)
在main.js文件中:

new Vue({
 render: h => h(App),
 beforeCreate() {
     // 1
    Vue.prototype.$bus = this
 }
}).$mount('#app')

2: 学生要去背书包
在Student.vue中定义一个事件叫背书包。

<template>
  <div class="student">
    <h1>{{msg}}</h1>
    <!-- 父子组件传信息    -->
    <button @click="StudentForHomeWork()">学生到学校</button>
  </div>
</template>
<script>
export default {
  name: 'HelloWorld',
  data(){
    return{
      msg:'欢迎来到学生页面',
      student:{
        name:'zebra',
        age: '18',
        sex: '男'
      }
    }
  },
  methods:{
    // 2 准备数据
    StudentForHomeWork(){
   this.$bus.$emit('busToSchool',this.student.name)
   }
 },
}
</script>
<style scoped>
.student{
  background-color: pink;
}
</style>

3 学校收到作业
在School.vue文件中收到作业

<template>
  <div class="school">
   <h2> {{msg}}</h2>
  </div>
</template>
<script>
export default {
  name: 'School',
  data(){
  return{
    msg:'欢迎来到学校页面',
  }
},
mounted(){
  this.$bus.$on('busToSchool',(data)=>{
    console.log('学校收到了学生作业:',data)
  })
},
methods:{}
}
</script>

<style scoped>
.school{
  background-color: grey;
  padding: 100px;
  margin-top: 10px;
}
</style>

App.vue文件如下

<template>
  <div id="app">
     <h2>{{appData}},学生的姓名是:{{studentName}}</h2>
    <Student/>
    <!--  自定义组件传信息 第一种   -->
     <School/>
    <!--  自定义组件传信息 第二种  -->
<!--    <School ref="school" ></School>-->
  </div>
</template>

<script>
import Student from './components/Student.vue'

import School from './components/School.vue'
export default {
  name: 'App',
  components: {
    Student,
    School
  },
  data(){
    return{
      appData: '你好啊',
      studentName:''
    }
  },
  
 beforeDestroy() {
    this.$bus.$off('busToSchool')
    console.log('销毁这个事件')
  }
}
</script>

<style>
#app{
  background-color: darkolivegreen;
  padding: 100px;
}
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值