1. 基本知识
在 Vue 3 中,emit 是一种机制,用于在子组件中触发事件,并在父组件中监听这些事件
提供一种组件间通信的方式,尤其是在处理父子组件数据传递和交互时非常有用
一共有两种方式
1.1 emit
子组件中使用emit
<template>
<button @click="handleClick">Click me</button>
</template>
<script>
export default {
name: 'ChildComponent',
methods: {
handleClick() {
this.$emit('custom-event', 'Hello from child');
}
}
}
</script>
父组件监听子组件:
<template>
<div>
<ChildComponent @custom-event="handleCustomEvent" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
name: 'ParentComponent',
components: {
ChildComponent
},
methods: {
handleCustomEvent(payload) {
console.log(payload); // 输出 'Hello from child'
}
}
}
</script>
1.2 defineEmits
在 Vue 3 中,还可以使用 Composition API 的 defineEmits 方法来定义和使用 emit
子组件中定义和使用emit:
<template>
<button @click="emitEvent">Click me</button>
</template>
<script setup>
import { defineEmits } from 'vue';
const emit = defineEmits(['custom-event']);
function emitEvent() {
emit('custom-event', 'Hello from child with Composition API');
}
</script>
父组件监听子组件:
<template>
<div>
<ChildComponent @custom-event="handleCustomEvent" />
</div>
</template>
<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>
2. Demo
完整Demo如下:
- 创建子组件:
<template>
<button @click="emitEvent">Click me</button>
</template>
<script setup>
import { defineEmits } from 'vue';
const emit = defineEmits(['custom-event']);
function emitEvent() {
emit('custom-event', 'Hello from child with Composition API');
}
</script>
- 创建父组件:
<template>
<div>
<ChildComponent @custom-event="handleCustomEvent" />
<p>{{ message }}</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
import { ref } from 'vue';
export default {
name: 'ParentComponent',
components: {
ChildComponent
},
setup() {
const message = ref('');
function handleCustomEvent(payload) {
message.value = payload;
}
return {
message,
handleCustomEvent
};
}
}
</script>
- 应用组件:
<template>
<ParentComponent />
</template>
<script>
import ParentComponent from './components/ParentComponent.vue';
export default {
name: 'App',
components: {
ParentComponent
}
}
</script>
主入口文件:
import { createApp } from 'vue';
import App from './App.vue';
createApp(App).mount('#app');