Vue3 如何使用 Emit,你學會了嗎?
圖片
1. vue3 使用 emit
在 Vue 3 中,emit 是一種用于在子組件中觸發(fā)事件并在父組件中監(jiān)聽這些事件的機制。
這為組件間通信提供了一種方式,尤其是在處理父子組件數(shù)據(jù)傳遞和交互時非常有用。
Vue 3 支持兩種主要的方式來使用 emit:
1.1. 選項 API 方式
在傳統(tǒng)的選項 API 方式中,emit 是通過 this.$emit 來調用的。
例如:
// 子組件 ChildComponent.vue
<template>
  <button @click="handleClick">Click me</button>
</template>
<script>
export default {
  name: 'ChildComponent',
  methods: {
    handleClick() {
      this.$emit('custom-event', 'Hello from child');
    }
  }
}
</script>在父組件中,你可以監(jiān)聽子組件發(fā)出的事件:
<ChildComponent @custom-event="handleCustomEvent" />
<script>
import ChildComponent from './ChildComponent.vue';
export default {
  name: 'ParentComponent',
  components: { ChildComponent },
  methods: {
    handleCustomEvent(payload) {
      console.log(payload); // 輸出 'Hello from child'
    }
  }
}
</script>這種方式簡單直觀,適用于不需要嚴格類型檢查的場景 。
1.2. 組合 API 方式
Vue 3 引入了 Composition API,提供了更強大的工具集來構建組件。
在這種情況下,你可以使用 defineEmits 函數(shù)來定義和使用 emit:
// 子組件 ChildComponent.vue
<template>
  <button @click="emitEvent">Click me</button>
</template>
<script>
import { defineEmits } from 'vue';
export default {
  setup() {
    const emit = defineEmits(['custom-event']);
    
    function emitEvent() {
      emit('custom-event', 'Hello from child with Composition API');
    }
    return { emitEvent };
  }
}
</script>同樣地,在父組件中監(jiān)聽子組件發(fā)出的事件:
<ChildComponent @custom-event="handleCustomEvent" />
<script>
import ChildComponent from './ChildComponent.vue';
export default {
  name: 'ParentComponent',
  components: { ChildComponent },
  methods: {
    handleCustomEvent(payload) {
      console.log(payload); // 輸出 'Hello from child with Composition API'
    }
  }
}
</script>這種方法允許你在組件的 setup 函數(shù)中定義 emit,并且可以更靈活地處理組件間的通信 。
1.3. 驗證函數(shù)
Vue 3 允許你在 emits 選項中使用驗證函數(shù),以確保傳遞給 $emit 的參數(shù)符合預期。
驗證函數(shù)應該返回一個布爾值來指示事件參數(shù)是否有效。
這有助于防止在生產環(huán)境中由于錯誤的參數(shù)而導致的問題 。
1.4. 事件總線
對于更加復雜的跨組件通信,你可以使用事件總線(Event Bus)。
事件總線允許組件之間通過一個中心化的實例來發(fā)送和接收事件,這種方式特別適用于那些沒有直接父子關系的組件間通信。
例如,使用 mitt 庫可以輕松實現(xiàn)事件總線的功能 。
1.5. 注意事項
當使用 emit 時,有幾個注意事項:
- 確保在父組件中正確監(jiān)聽子組件發(fā)出的事件。
 - 在子組件中觸發(fā)事件時,確保傳遞正確的參數(shù)。
 - 如果使用 Composition API,記得導入 defineEmits 并正確使用它。
 
通過以上方式,你可以有效地利用 emit 在 Vue 3 中實現(xiàn)父子組件間的通信。
此外,如果你的應用中有多個組件需要互相通信,考慮使用事件總線或者更高級的解決方案如 Vuex 來管理狀態(tài)。















 
 
 



















 
 
 
 