安裝消息訂閱與發(fā)布安裝包
npm i pubSub-js --save
消息發(fā)布
<template>
<div class="school">
<h4>大學名稱是:{{ schoolName }}</h4><el-button @click="sendSchoolName(schoolName)">發(fā)送</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>