main.js
import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false //创建vm new Vue({ el: '#app', render: h => h(App), beforeCreate() { //安装全局事件总线 Vue.prototype.$bus = this } })
School.vue
<template> <div class="demo"> <h2>学校名称:{{schoolName}}</h2> <h2>学校地址:{{address}}</h2> </div> </template> <script> export default { name: 'School', data() { return { schoolName: '二中', address: '上海' } }, mounted() { this.$bus.$on('hello', (data) => { console.log('我是School组件收到了数据', data); }) }, //解绑当前组件所用的事件 beforeDestroy() { this.$bus.$off('hello') } } </script> <style scoped> .demo { background-color: pink; } </style>
Student.vue
<template> <div class="demo"> <h2>学生姓名:{{name}}</h2> <h2>学生年龄:{{age}}</h2> <button @click="sendStudentname">把学生名给School组件</button> </div> </template> <script> export default { name: 'Student', data() { return { name: '张三', age: 19 } }, methods: { sendStudentname() { this.$bus.$emit('hello', 666) } }, } </script> <style> .demo { background-color: skyblue; } </style>