Vue3實戰(zhàn)筆記(47)— 一探emit奧秘——組件間通信的藝術(shù)與實踐

前言

Vue封裝了自定義組件之后,如果子組件想要向父組件傳遞數(shù)據(jù)該怎么辦?

Vue.js 中的 emit 方法就是主要用于組件間的通信,特別是父組件與子組件之間的通信機制。它是 Vue 組件內(nèi)部觸發(fā)自定義事件并向父級組件傳遞數(shù)據(jù)的一種方式。


一、Vue 2 中的emti

在 Vue 組件中,當(dāng)你想要向父組件傳遞信息或通知父組件某個狀態(tài)發(fā)生了改變時,可以使用 $emit。通常情況下,子組件無法直接修改父組件的數(shù)據(jù),而是通過定義并觸發(fā)一個自定義事件,由父組件監(jiān)聽并在回調(diào)函數(shù)中作出響應(yīng)。

但是要注意,Vue2和Vue3的用法略有不同。
Vue 2 示例:

<!-- 父組件(parent-component.vue) -->
<template>
  <div>
    <child-component @child-event="handleChildEvent" />
  </div>
</template>

<script>
import ChildComponent from './child-component.vue';

export default {
  components: { ChildComponent },
  methods: {
    handleChildEvent(data) {
      console.log('接收到的數(shù)據(jù):', data);
    }
  }
}
</script>
<!-- 子組件(child-component.vue) -->
<template>
  <div>
    <button @click="sendData">發(fā)送數(shù)據(jù)</button>
  </div>
</template>

<script>
export default {
  methods: {
    sendData() {
      this.$emit('child-event', '這是發(fā)送的數(shù)據(jù)');
    }
  }
}
</script>

在這個例子中,子組件 child-component.vue 使用 $emit 方法觸發(fā)了一個名為 child-event 的自定義事件,并傳入了一個參數(shù) data。父組件 parent-component.vue 通過監(jiān)聽 child-event 事件并定義一個處理函數(shù) handleChildEvent 來接收數(shù)據(jù)。當(dāng)子組件中的按鈕被點擊時,會觸發(fā) child-event 事件,父組件會接收到數(shù)據(jù)并在控制臺中打印出來。

二、Vue 3的emit

Vue 3 示例:


<!-- 父組件(parent-component.vue) -->
<template>
  <div>
    <child-component ref="childRef" />
  </div>
</template>

<script>
import ChildComponent from './child-component.vue';

export default {
  components: { ChildComponent },
  setup() {
    const childRef = ref(null);

    function handleChildEvent(data) {
      console.log('接收到的數(shù)據(jù):', data);
    }

    onMounted(() => {
      childRef.value.$on('child-event', handleChildEvent);
    });

    onUnmounted(() => {
      childRef.value.$off('child-event', handleChildEvent);
    });

    return { childRef };
  }
}
</script>

<!-- 子組件(child-component.vue) -->
<template>
  <div>
    <button @click="sendData">發(fā)送數(shù)據(jù)</button>
  </div>
</template>

<script>
export default {
  methods: {
    sendData() {
      this.$emit('child-event', '這是發(fā)送的數(shù)據(jù)');
    }
  }
}
</script>

在這個例子中,父組件 parent-component.vue 使用 ref 屬性創(chuàng)建了一個引用,并將其分配給子組件。在 setup 函數(shù)中,定義了一個處理函數(shù) handleChildEvent 用于處理自定義事件。在 onMounted 鉤子中,使用子組件引用的 on 方法監(jiān)聽 child-event 事件。在 onUnmounted 鉤子中,使用子組件引用的off 方法取消對 child-event 事件的監(jiān)聽。當(dāng)子組件中的按鈕被點擊時,會觸發(fā) child-event 事件,父組件會接收到數(shù)據(jù)并在控制臺中打印出來。


總結(jié)

做一個積極向上的人,給自己和他人帶來陽光。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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