Vue - 全局事件總線


全局事件總線

一種組件間的通信方式,適用於任意組件間通信。

使用方式

1.安裝全局事件總線

new Vue({
  render: h => h(App),
  beforeCreate() {
    Vue.prototype.$bus = this
  }
}).$mount('#app')

2.使用事件總線
接收數據:A組件想接收數據,則在A組件中給$bus綁定自定義事件,事件的回調留在A組件身上。

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

<script>
export default {
  name: "School",
  data(){
    return{
      receiveName:""
    }
  },
  methods:{
    rec(name){
      console.log("准備接收數據");
      console.log("接收到學生姓名"+name);
      this.receiveName = name
    }
  },
  mounted() {
    this.$bus.$on("receive",this.rec)
  }
}
</script>

提供數據:this.$bus.$emit('自定義事件名',數據)

<template>
  <div>
    <button @click="sendName">發送學生信息給學校</button>
  </div>
</template>

<script>
export default {
  name: "Student",
  data(){
    return{
      name:"張三"
    }
  },
  methods:{
    sendName(){
      this.$bus.$emit("receive",this.name)
    }
  }
}
</script>

最好在beforeDestory鈎子中,用$off去解綁當前組件所用到的事件。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM