安装全局事件总线
在main.js中写入如下代码
beforeCreate () {
Vue.prototype.$bus = this //安装全局事件总线
}
触发事件
<template>
<div class="school">
<h4>大学名称是:{{ schoolName }}</h4><el-button @click="sendSchoolName(schoolName)">发送</el-button>
</div>
</template>
<script>
export default {
name: 'School',
data () {
return {
schoolName: 'XXX大学'
}
},
methods: {
sendSchoolName (val) {
this.$bus.$emit('getSchoolName', val) //触发事件
}
}
}
</script>
接收事件
<template>
<div class="student">
<h4>我的名字是{{ name }},我今年{{ age }}岁<span v-if="schoolName">我是{{ schoolName}}的学生</span> </h4>
</div>
</template>
<script>
export default {
name: 'Student',
data () {
return {
name: 'Tom',
age: 18,
schoolName: ''
}
},
mounted () {
this.getSchoolName()
},
methods: {
getSchoolName () {
// 接收事件
this.$bus.$on('getSchoolName', (data) => {
this.schoolName = data
})
}
},
beforeDestroy () {
this.$bus.$off('getSchoolName')
}
}
</script>