VUE元件--emit 事件外送
使用Vue 框架的時候,子元件要傳遞事件給父元件可以使用 emit。
在這裡要注意,子元件對父元件的事件沒有冒泡機制。
預設在子元件觸發事件的 DOM 元素上可以直接使用 $emit
直接在子元件的 DOM 元素上使用$emit,就可以把事件傳遞到父元件,並不需要 defineEmits 定義子元件的 emit 事件才能使用。
<button @click="$emit('someEvent')">click me</button>讓我們看一下範例:
- 先在子元件的
<button>上綁定$emit
使用 v-on 綁定事件,@click="$emit('increaseBy', 2)",再使用 $emit 傳遞到父元件,increaseBy 是父元件接收的方法, 2 則是傳給父層接收方法的參數。
<script setup>
import { ref } from 'vue';
// defineEmits(['increaseBy']);
</script>
<template>
<h2>{{ msg }}</h2>
<button @click="$emit('increaseBy', 2)">ADD</button>
Count: {{ count }}
</template>- 在父元件上接收透過
v-on來接收 子元件的emit
在這裡 <HelloWorld @increase-by="increaseCount" /> 同樣要遵守「前內元件,後外元件」的規則,@increase-by 是子元件定義的 emit 事件,而 increaseCount 則是父元件的接收方法。
再以下程式碼中透過一個涵式接收:
<script setup>
import { ref } from 'vue';
import HelloWorld from './components/HelloWorld.vue';
const countParent = ref(0);
const increaseCount = (n) => {
countParent.value += n;
};
</script>
<template>
<HelloWorld @increase-by="increaseCount" />
<h3>countParent:{{ countParent }}</h3>
</template>
這種方式也可以
<MHelloWorld @increase-by="(n) => count += n" />官方建議透過 defineEmits 定義 emit 事件
Vue 官方建議明確地在