【Vue3】组件通信之自定义事件
发布时间
阅读量:
阅读量
【Vue3】组件通信之自定义事件
- 背景
- 简介
- 开发环境
- 开发步骤及源码
- 总结
背景
伴随年岁的增长
简介
本文介绍 Vue3 中如何通过自定义事件实现子组件向父组件传数据。
Vue3 中组件间通信包括:
父组件通过传递数据的方式向子组件实现通信与交互功能。具体实现方式包括:
-
props属性
-
v-model绑定
-
$refs引用
默认插槽与具名插槽两种类型- 子组件向父组件传数据
propsv-model$parent- 自定义事件
- 作用域插槽
- 子组件向父组件传数据
父组件向下传递数据给其直接子组件(即孙子组件)。
attrs
provider & inject
- 任意组件间传数据
mittPinia
开发环境
| 分类 | 名称 | 版本 |
|---|---|---|
| 操作系统 | Windows | Windows 11 |
| IDE | Visual Studio Code | 1.91.1 |
开发步骤及源码
Vue3
Vue3
Vue3
Vue3
<template>
<div class="parent">
<h1>父组件</h1>
<h2>Blog数量:{{ blogs.length }}</h2>
<h2>浏览数量:{{ readTimes }}</h2>
<!-- 给子组件绑定了一个 sync-read-times 事件,只要 sync-read-times 被触发,其指向的 syncReadTimes 函数就会被调用 -->
<Blog :blogs="blogs" :author="author" @sync-read-times="syncReadTimes" />
</div>
</template>
<script setup lang="ts">
import Blog from './components/Blog.vue'
import { reactive, ref } from 'vue'
const author = ref('Nick')
const blogs = reactive([
{ id: '001', title: '美国大选', content: '美国大选将于...' },
{ id: '002', title: '奥运奖牌', content: '截止今日奥运奖牌榜...' },
{ id: '003', title: '俄乌战争', content: '乌克兰单方面提出希望和谈...' },
{ id: '004', title: '巴以冲突', content: '巴以冲突最新战况...' },
])
const readTimes = ref(0)
function syncReadTimes(value) {
readTimes.value += value
}
</script>
<style scoped lang="scss">
.parent {
background-color: orange;
padding: 20px;
}
</style>

2> 声明子组件采用 defineEmits 函数接收到父组件的自定义事件 sync-read-times;接着设置 <button> 的点击事件以触发该自定义事件。
<template>
<div class="content">
<h1>子组件</h1>
<div class="blog" v-for="blog in blogs" :key="blog.id">
<div class="blog-title">标题:{{ blog.title }}</div>
<div class="blog-author">作者:{{ author }}</div>
<div class="blog-content">{{ blog.content }}</div>
<button @click="emits('sync-read-times', 1)">浏览量+1</button>
</div>
</div>
</template>
<script setup lang="ts">
const data = defineProps(['author', 'blogs'])
// 声明事件
const emits= defineEmits(['sync-read-times'])
</script>
<style scoped lang="scss">
.content {
background-color: aquamarine;
padding: 20px;
.blog {
border: 1px solid gray;
border-radius: 5px;
padding: 0 10px;
margin-top: 5px;
div {
padding: 10px 5px;
}
.blog-title {
font-weight: bold;
}
.blog-author {
font-size: small;
font-style: italic;
}
.blog-content {
font-size: small;
}
button {
margin: 10px 0;
}
}
}
</style>

运行命令 npm run dev 启动应用程序,并使浏览器将访问:http://localhost:5173/。单击子组件内的按钮会导致父组件中的 访问次数 随着按钮被点击的次数增多。

总结
使用自定义事件实现子组件向父组件传数据:
- 父组件应在子组件标签中设定自定义事件。其格式规定了
@符号后的结构:即"@事件名='函数名'"的形式。例如,在本例中使用了 @ sync-read-times = " syncReadTimes "; - 子组件通过调用 defineEmits 函数声明对父组件的自定义事件响应;该函数参数为一个包含所有相关自定义事件名称的数组;
- 子组件可根据实际需求发起对特定自定义事件的触发;该触发操作的第一个参数为事 件名称;后续参数则传递所需数据给父组件。
全部评论 (0)
还没有任何评论哟~
