VUE3----组件通信(消息订阅-发布)
安装pubsub-jsnpm i pubsub-js --save发布消息<template><button @click="sendStudentName">把学生名给School组件</button></template><script>import pubsub from "pubsub-js";import {reactive}
·
安装pubsub-js
npm i pubsub-js --save
发布消息
<template>
<button @click="sendStudentName">把学生名给School组件</button>
</template>
<script>
import pubsub from "pubsub-js";
import {reactive} from "vue";
export default {
name: "Student",
setup(){
const person=reactive({
name:'张三',
age:30,
})
const sendStudentName = () => {
// 发布消息
pubsub.publish('hello',person)
}
return{
sendStudentName,
person
}
}
}
</script>
订阅消息
<template>
<div>
{{person.name}}==={{person.age}}
</div>
</template>
<script>
import {onMounted, onUnmounted, reactive} from "vue";
import pubsub from "pubsub-js";
export default {
name: "School",
setup(){
let person=reactive({})
const demo = (msgName,data) => {
console.log('msgName====',msgName)
console.log('data====',data)
Object.assign(person,data)
}
let pubId=null
onMounted(()=>{
// 订阅消息
pubId=pubsub.subscribe('hello',demo)
})
onUnmounted(()=>{
pubsub.unsubscribe(pubId)
})
return{
demo,
person
}
}
}
</script>
更多推荐
已为社区贡献4条内容
所有评论(0)