安装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>
Logo

前往低代码交流专区

更多推荐