Vue 父子组件传值演示
本页面展示了 Vue 3 中父子组件如何通过 props 传递数据和通过 emit 事件进行通信
Vue 示例代码
父组件 (ParentComponent.vue)
<!-- 父组件 ParentComponent.vue -->
<template>
<!-- 父组件模板 -->
<div class="parent">
<h2>父组件</h2>
<!-- 使用子组件,传递props并监听事件 -->
<ChildComponent
:message="message"
:count="count"
@update-count="handleUpdateCount"
@send-message="handleMessage"
/>
</div>
</template>
<script setup>
// 导入组合式API函数
import { ref } from 'vue'
// 导入子组件
import ChildComponent from './ChildComponent.vue'
// 1. 定义响应式数据
const message = ref('来自父组件的消息')
const count = ref(0)
// 2. 定义处理子组件事件的方法
const handleUpdateCount = (value) => {
// 接收子组件传递的值并更新count
count.value += value
}
const handleMessage = (msg) => {
// 接收子组件的消息
message.value = msg
console.log('收到子组件消息:', msg)
}
</script>子组件 (ChildComponent.vue)
<!-- 子组件 ChildComponent.vue -->
<template>
<!-- 子组件模板 -->
<div class="child">
<h3>子组件</h3>
<!-- 展示从父组件接收的props -->
<p>消息: {{ message }}</p>
<p>计数: {{ count }}</p>
<!-- 向父组件发送事件 -->
<button @click="increment">增加计数</button>
<button @click="sendMessage">发送消息</button>
</div>
</template>
<script setup>
// 1. 使用defineProps定义接收的props
// 第一种写法:数组形式(简单场景)
// const props = defineProps(['message', 'count'])
// 第二种写法:对象形式(推荐,可以设置类型和默认值)
const props = defineProps({
message: {
type: String, // 指定类型
default: '默认消息', // 设置默认值
required: true // 是否必填
},
count: {
type: Number,
default: 0,
required: true
}
})
// 2. 使用defineEmits定义可以触发的事件
const emit = defineEmits(['update-count', 'send-message'])
// 3. 定义方法,通过emit向父组件发送事件
const increment = () => {
// 触发事件并传递数据
emit('update-count', 1)
}
const sendMessage = () => {
// 触发事件并传递数据
emit('send-message', '来自子组件的消息')
}
</script>关键知识点
- Props 传值:父组件通过 :属性名="值" 的方式向子组件传递数据
- Props 验证:子组件使用 defineProps 定义接收的 props,可以设置类型、默认值和是否必填
- 事件通信:子组件通过 defineEmits 定义可以触发的事件,使用 emit 触发事件
- 单向数据流:数据只能从父组件流向子组件,子组件通过事件通知父组件更新数据
- 响应式数据:使用 ref 和 reactive 创建响应式数据,当数据变化时视图自动更新
使用说明
1. 本示例展示了 Vue 3 中父子组件通信的基本方法
2. 父组件通过 props 向子组件传递数据,子组件通过 emit 事件向父组件发送消息
3. 实际项目中请使用 Vue 语法编写组件