在 Vue 3 中,使用组合式 API(Composition API)时,可以通过 emit
来声明和触发自定义事件。emit
是一个函数,用于从子组件向父组件发送事件。下面是一个详细的示例,展示如何在 Vue 3 中使用 emit
来声明和触发事件。
示例:使用 emit
触发事件
假设我们有一个子组件 ChildComponent
,它包含一个按钮,点击按钮时会触发一个自定义事件 myEvent
,并将一个值传递给父组件。
1. 创建子组件 ChildComponent.vue
在 src/components
目录下创建一个名为 ChildComponent.vue
的文件,内容如下:
<template>
<div>
<h2>子组件</h2>
<button @click="handleClick">点击触发事件</button>
</div>
</template>
<script setup>
import { defineEmits } from 'vue';
// 定义要触发的事件
const emit = defineEmits(['myEvent']);
// 处理按钮点击事件
const handleClick = () => {
const message = 'Hello from ChildComponent';
emit('myEvent', message);
};
</script>
<style scoped>
button {
margin: 5px;
padding: 10px;
}
</style>
解释
-
模板部分 (
<template>
):- 包含一个按钮,点击按钮时触发
handleClick
方法。
- 包含一个按钮,点击按钮时触发
-
脚本部分 (
<script setup>
):- 使用
defineEmits
函数来定义要触发的事件myEvent
。 - 在
handleClick
方法中,使用emit
函数触发myEvent
事件,并传递一个值message
。
- 使用
-
样式部分 (
<style scoped>
):- 定义了一些基本的样式,使按钮看起来更好看。
2. 创建父组件 ParentComponent.vue
在 src/components
目录下创建一个名为 ParentComponent.vue
的文件,内容如下:
<template>
<div>
<h1>父组件</h1>
<ChildComponent @myEvent="handleMyEvent" />
<p>接收到的消息: {{ message }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
// 定义一个响应式的变量来存储接收到的消息
const message = ref('');
// 处理子组件触发的事件
const handleMyEvent = (msg) => {
message.value = msg;
};
</script>
<style scoped>
p {
margin: 10px;
font-size: 1.2em;
}
</style>
解释
-
模板部分 (
<template>
):- 包含一个
ChildComponent
组件,并通过@myEvent
监听子组件触发的myEvent
事件。 - 使用插值表达式
{{ message }}
显示接收到的消息。
- 包含一个
-
脚本部分 (
<script setup>
):- 使用
ref
创建一个响应式的变量message
,用于存储从子组件接收到的消息。 - 定义
handleMyEvent
方法,该方法会在子组件触发myEvent
事件时被调用,并更新message
的值。
- 使用
-
样式部分 (
<style scoped>
):- 定义了一些基本的样式,使段落看起来更好看。
3. 使用组件
在 src/App.vue
中引入并使用 ParentComponent
组件:
<template>
<div id="app">
<ParentComponent />
</div>
</template>
<script>
import ParentComponent from './components/ParentComponent.vue';
export default {
name: 'App',
components: {
ParentComponent
}
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
解释
-
模板部分 (
<template>
):- 包含一个
ParentComponent
组件。
- 包含一个
-
脚本部分 (
<script>
):- 导入
ParentComponent
组件并在components
对象中注册。
- 导入
-
样式部分 (
<style>
):- 定义了一些基本的样式,使应用看起来更好看。
运行项目
在项目根目录下运行以下命令启动开发服务器:
npm run serve
打开浏览器访问 http://localhost:8080
,你应该能看到一个父组件和子组件的结构。点击子组件中的按钮时,父组件会接收到子组件传递的消息并显示出来。