安装消息订阅与发布安装包
npm i pubSub-js --save
消息发布
<template>
<div class="school">
<h4>大学名称是:{{ schoolName }}</h4><el-button @click="sendSchoolName(schoolName)">发送</el-button>
</div>
</template>
<script>
import pubSub from 'pubsub-js'
export default {
name: 'School',
data () {
return {
schoolName: 'XXX大学'
}
},
methods: {
sendSchoolName (val) {
pubSub.publish('getSchoolName', val)
}
}
}
</script>
消息订阅
<template>
<div class="student">
<h4>我的名字是{{ name }},我今年{{ age }}岁<span v-if="schoolName">我是{{ schoolName}}的学生</span> </h4>
</div>
</template>
<script>
import pubSub from 'pubsub-js'
export default {
name: 'Student',
data () {
return {
name: 'Tom',
age: 18,
schoolName: ''
}
},
mounted () {
this.getSchoolName()
},
methods: {
getSchoolName () {
// 接收事件
this.pubSubId = pubSub.subscribe('getSchoolName', (masName, data) => {
this.schoolName = data
})
}
},
beforeDestroy () {
pubSub.unsubscribe(this.pubSubId)
}
}
</script>