1. 程式人生 > 其它 >Vue - 訊息訂閱與釋出

Vue - 訊息訂閱與釋出

一種元件間通訊方式,適用於任意元件間通訊。

使用步驟

1.安裝pubsub: npm i pubsub-js
2.引入:import pubsub from 'pubsub-js'
3.接收資料:A元件想接收資料,則在A元件中訂閱訊息,訂閱的回撥留在A元件自身。pubsub.subscribe('xxx',回撥函式)

<template>
  <div>
    <h2>{{receiveName}}</h2>
  </div>
</template>

<script>
import pubsub from 'pubsub-js'
export default {
  name: "School",
  data(){
    return{
      receiveName:""
    }
  },
  mounted() {
    this.pid = pubsub.subscribe("receiver",(msgName,data) =>{
      console.log(msgName+"訂閱成功!");
      this.receiveName = data;
    })
  }
}
</script>

4.提供資料:pubsub.publish('xxx',資料)

<template>
  <div>
    <button @click="send">傳送訂閱</button>
  </div>
</template>

<script>
import pubsub from 'pubsub-js'
export default {
  name: "Student",
  data(){
    return{
      name:"張三"
    }
  },
  methods:{
    send(){
      pubsub.publish('receiver',this.name);
    }
  }
}
</script>

5.最好在beforeDestory鉤子中,用pubsub.unsubscribe(pid)取消訂閱。