vue3 中使用事件總線,實(shí)現(xiàn)兄弟組件傳值

一、vue2 中使用事件總線,實(shí)現(xiàn)兄弟組件傳值

  1. 在 main.js 中定義事件總線
new Vue({
  router,
  store,
  render: (h) => h(App),
  beforeCreate() {
    Vue.prototype.$bus = this;
  },
}).$mount("#app");
  1. 在組件A中監(jiān)聽事件
mounted() {
    this.$bus.$on("getUserInfo", (data) => {console.log(data)});
},
destroyed() {
    this.$bus.$off("getUserInfo");
},
  1. 在組件B中觸發(fā)事件
mounted() {
    setTimeout(() => {
        this.$bus.$emit("getUserInfo", { username: "alias", password: "123456" });
    }, 1000);
},

二、vue3 中使用事件總線,實(shí)現(xiàn)兄弟組件傳值

在vue3中 $on、$off、$once 被移除,$emit 保留
解決方案:使用第三方庫 mitt 代替 $on、$off、$once 實(shí)現(xiàn)兄弟組件傳值

  1. 安裝 mitt
npm install mitt -S
  1. 在 main.js 中把事件總線綁定到全局屬性上
import mitt from 'mitt'
app.config.globalProperties.Bus = mitt()
  1. 在組件A中監(jiān)聽事件
<script setup>
import { getCurrentInstance, onUnmounted } from 'vue'
const { $bus } = getCurrentInstance().appContext.config.globalProperties

$bus.on('getUserInfo', (data) => console.log(data))

onUnmounted(() => {
  $bus.off('getUserInfo')
})
</script>
  1. 在組件B中觸發(fā)事件
import { getCurrentInstance, onMounted } from 'vue';
const { $bus } = getCurrentInstance().appContext.config.globalProperties

onMounted(()=>{
  setTimeout(() => {
    $bus.emit("getUserInfo", { username: "alias", password: "123456" });
  }, 1000);
})
  1. 官方示例
import mitt from 'mitt'

const emitter = mitt()

// listen to an event
emitter.on('foo', e => console.log('foo', e) )

// listen to all events
emitter.on('*', (type, e) => console.log(type, e) )

// fire an event
emitter.emit('foo', { a: 'b' })

// clearing all events
emitter.all.clear()

// working with handler references:
function onFoo() {}
emitter.on('foo', onFoo)   // listen
emitter.off('foo', onFoo)  // unlisten
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容