Vue---全局事件总线(实现任意组件间通信)
目录
总结
一、实现
main.js
重要代码:
school.vue
重要代码
student.vue
重要代码
总结
一、实现
案例:由student.vue 向school.vue传输数据 其两文件之间的关系是兄弟关系
main.js
// 该文件是整个项目的入口文件
// 引入vue,这个vue不能解析template配置项
import Vue from 'vue'
// 下面这个是引入完整版的vue。这个vue能解析template配置项
// import Vue from 'vue/dis/vue'
// 引入APP组件,它是所有组件的父组件
import App from './App.vue'
Vue.prototype.x={a:10}
// 关闭vue的生产提示
Vue.config.productionTip = false
// 创建vue实例对象---vm
new Vue({
el:'#app',
render: h => h(App),
//这个里面的this是vm 此时模板还没有解析
beforeCreate(){
// Vue.prototype在原型上定义
// 这个地方为什么不写等于vm? 因为当这个new Vue执行完成之后才有vm 我们现在还是在new vm中
// 安装全局事件总线
Vue.prototype.$bus = this
}
})
重要代码:
//这个里面的this是vm 此时模板还没有解析
beforeCreate(){
// Vue.prototype在原型上定义
// 这个地方为什么不写等于vm? 因为当这个new Vue执行完成之后才有vm 我们现在还是在new vm中
// 安装全局事件总线
Vue.prototype.$bus = this
}
school.vue
<template>
<div class="school">
<h2> 学校名称:{
{name}}</h2>
<h2> 学校地址:{
{address}}</h2>
</div>
</template>
<script>
export default {
name:'School',
data(){
return{
name:'尚硅谷',
address:'北京昌平',
}
},
mounted(){
this.$bus.$on('hello',(data)=>{
console.log('我是School组件,收到了数据',data)
})
},
beforeDestroy(){
this.$bus.$off('hello')
}
}
</script>
<style scoped>
.school{
background-color: skyblue;
padding:5px;
margin-top:30px;
}
</style>
重要代码
mounted(){
this.$bus.$on('hello',(data)=>{
console.log('我是School组件,收到了数据',data)
})
},
beforeDestroy(){
this.$bus.$off('hello')
}
student.vue
<template>
<!-- <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:'男',
age:18
}
},
methods:{
sendStudentName(){
this.$bus.$emit('hello',this.name)
}
}
}
</script>
<style scoped>
.student{
background-color: red;
padding:5px;
margin-top:30px;
}
</style>
重要代码
<button @click="sendStudentName">把学生名给School组件</button>
methods:{
sendStudentName(){
this.$bus.$emit('hello',this.name)
}
}
还没有评论,来说两句吧...