1.在Vue的原型上(Vue.prototype)安装全局事件总线$bus,因为需要$bus能够进行$on,$emit,$off,所以赋给$bus的值必须能找到Vue.protopype,所以$bus是在main.js中创建的vm。这样,所有的vc都能通过查找原型的方式找到$bus
main:
import Vue from "vue"
import App from "./App.vue"
new Vue({
render:h => h(App),
beforeCreate() {
//在创建之前就给bus赋值,否则执行完挂载等操作APP就放到页面上去了,此时School还没接收到Student中传过来的内容,就已经报错了
Vue.prototype.$bus=this
},
}).$mount("#div1")
App.vue:
<template>
<div >
<div id="makeTodoList">
<School/>
<Student/>
</div>
</div>
</template>
<script>
import School from "./src2/School.vue"
import Student from "./src2/Student.vue"
export default {
components: {School,Student},
name:"App",
</script>
<style scoped>
</style>
School.vue
<template>
<div>
<h1>{{name}}</h1>
<h1>{{age}}</h1>
</div>
</template>
<script>
export default {
name:"School",
data() {
return {
name:"",
age:12
}
},
mounted(){
this.$bus.$on("demo",(studentName)=>{//这里要用箭头函数或者写在methods里的函数,让this指向vc
this.name=studentName
})
},
beforeDestroy(){
this.$bus.$off("demo")
}
}
</script>
<style>
div{
background-color: orange;
}
</style>
Student.vue:
<template>
</template>
<script>
export default {
name: 'Student',
data() {
return {
name:"lili"
}
},
mounted(){
this.$bus.$emit("demo",this.name)
}
}
</script>
<style scoped>
</style>