0
点赞
收藏
分享

微信扫一扫

全局事件

main.js文件:

import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
//1.全局事件:多个组件调用一个地方(如:X),由这么一个地方在返回各个组件想要的数据
//如何让多个组件调用这么一个地方(X)
//1.让所有组件可以看到他 :Vue.prototype.x 在vue的原型上添加属性;可以所有组件都可以调用
//2.直接在vm里面写入,目的是第一条简便写法
// beforeCreate(){ 使用beforecreate的目的在没有初始化之前写入以下方法
// Vue.prototype.$bus = this //$bus 任意起的名字 意思是总线的意思 this指向vm
// }
//3.$on(点击) $emit(传递) $off()
//4.school想要属性值,在找vm要,vm将student上值给school
new Vue({
el:'#app',
render: h => h(App),
//安装全局事件总线 beforeCreate = 在还没有初始化之前
beforeCreate(){
Vue.prototype.$bus = this //$bus 任意起的名字 意思是总线的意思
}
})

  student.vue文件

<template>
<div class="demo">
<h3>学生姓名:{{name}}</h3>
<button @click='wsx'>把学生姓名给school</button>
</div>
</template>

<style>
.demo{
color: #42B983;
}
</style>

<script>
export default {
name:'Student',
data(){
return {
name:'wei1111 '
}
},
mounted(){
//console.log('Student',this.x)
},
//当点击button,把值传给vue.prototype
methods:{
wsx(){

this.$bus.$emit('hello',111)
}
}
}
</script>


<style>
.demo{
color: #42B983;
}
</style>

  scholl.vue文件

<template>
<div class="demo">
<h3>学校名称:{{name}}</h3>
</div>
</template>

<script>
export default {

name:'School',
data(){
return{
name:'渲染学校'
}
},
mounted(){
//console.log('School',this.x)
//this指向school实例对象上vue.prototype
//在由main受到的student值给school
this.$bus.$on('hello',(data)=>{
console.log('我是school,接收到了student数据',data)
});
},
//克隆完hello后,进行销毁
beforeDestroy(){
this.$bus.$off('hello')
}
}
</script>

<style scoped>
.demo{
color: red;
}
</style>

  

全局事件_App

 

举报

相关推荐

0 条评论