vue--day51--全局事件总线

1.main.js

/**
* 该文件是整个项目的入口文件
*/
//引入Vue
import Vue from 'vue'
// 引入App 组件 他是所有组件的父组件
import App from './App.vue'

//关闭vue 的生产提示
Vue.config.productionTip = false
// const Demo=Vue.extend({})
// const d=new Demo();
// Vue.prototype.x=d;
// 创建Vue 实例对象--vm
new Vue({
//将 app 组件放入到容器中
render: h => h(App),

beforeCreate(){
Vue.prototype.$bus=this // 安装全局事件总监
}
}).$mount('#app')

2.App.vue

<template>
<div class="app">

<h1>{{ msg }}</h1>
<Student></Student>
<School></School>
</div>
 
</template>

<script>
//样式的引入和这里有关系
import Student from './components/Student.vue';
import School from './components/School.vue';


export default {
name: 'App',
components: {
School,
Student,
},
data(){
return {
msg:'你好呀'
}
 
},

 
}
</script>

<style scoped>
.app{
background-color: brown;
}
</style>
 
3. School.vue
<template>
<!-- 组件的介绍 -->
<div class="school">

<h2>学校名称{{name}}</h2>
<h2>学校地址{{address}}</h2>
 

</div>
</template>



<script>


export default {
name:"School",
props:['receiveSchoolName'],
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:orange;
margin-top: 20px;
}

</style>
 
4.  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:'男',
 
}
},

methods:{
sendStudentName(){
this.$bus.$emit('hello',6666666)
}
}

 
 
 
 
 
}
</script>

<style scoped>
/* 组件的样式 */
.student{
background-color:cadetblue;
 
}

</style>



 
6. 总结

 

 
posted @ 2023-08-02 00:41  雪落无痕1  阅读(5)  评论(0编辑  收藏  举报