在 Vue 中,props
是实现父组件向子组件传递数据的主要方式。通过在子组件中定义 props
,父组件可以将数据传递给子组件进行展示或处理。
假设有一个父组件 Parent.vue
和一个子组件 Child.vue
。在父组件中,我们有一些数据,需要传递给子组件展示。
Child.vue
<template>
<div>
<p>来自父组件的消息: {{ message }}p>
div>
template>
<script setup>
const props = defineProps(['message']);
script>
在子组件中,使用 defineProps
宏来声明 props
。这里声明了一个名为 message
的 props
,它将接收来自父组件传递的数据。
Parent.vue
<template>
<div>
<child :message="parentMessage">child>
div>
template>
<script setup>
import Child from './Child.vue';
import { ref } from 'vue';
const parentMessage = ref('这是来自父组件的数据');
script>
在父组件中,引入 Child.vue
组件,并通过 :message="parentMessage"
将 parentMessage
数据传递给子组件的 message
props
。这样,子组件就能接收到父组件传递的数据并展示出来。
为了确保数据的正确性和稳定性,Vue 允许对 props
进行类型校验,并设置默认值。
Child.vue
<template>
<div>
<p>用户名: {{ user.name }}p>
<p>年龄: {{ user.age }}p>
div>
template>
<script setup>
const props = defineProps({
user: {
type: Object,
required: true,
default: () => ({ name: '匿名', age: 0 })
}
});
script>
在上述代码中:
type
用于指定 props
的类型,这里 user
被指定为 Object
类型。required
表示该 props
是否为必填项,设置为 true
表示必须传递。default
用于设置默认值。对于对象或数组类型的 props
,默认值必须是一个函数,函数返回默认的对象或数组。如果 props
不是必填且没有传递,子组件将使用默认值。Parent.vue
<template>
<div>
<child :user="userData">child>
div>
template>
<script setup>
import Child from './Child.vue';
import { ref } from 'vue';
const userData = ref({ name: '小明', age: 25 });
script>
父组件传递 userData
给子组件的 user
props
。如果父组件没有传递 user
,子组件会使用默认值 { name: '匿名', age: 0 }
。
$emit
触发自定义事件向父组件传递数据子组件向父组件传递数据通常通过触发自定义事件来实现。$emit
方法用于触发事件,并可以传递数据。
Child.vue
<template>
<div>
<button @click="sendDataToParent">点击传递数据给父组件button>
div>
template>
<script setup>
const emit = defineEmits(['data-sent']);
const sendDataToParent = () => {
const dataToSend = '这是子组件要传递的数据';
emit('data-sent', dataToSend);
};
script>
在子组件中,使用 defineEmits
宏定义可以触发的自定义事件 data-sent
。当按钮被点击时,sendDataToParent
方法会触发 data-sent
事件,并传递 dataToSend
数据。
父组件需要监听子组件触发的自定义事件,并处理传递过来的数据。
Parent.vue
<template>
<div>
<child @data-sent="handleChildData">child>
<p v-if="receivedData">接收到子组件的数据: {{ receivedData }}p>
div>
template>
<script setup>
import Child from './Child.vue';
import { ref } from 'vue';
const receivedData = ref('');
const handleChildData = (data) => {
receivedData.value = data;
};
script>
在父组件中,通过 @data-sent="handleChildData"
监听子组件触发的 data-sent
事件。当事件被触发时,handleChildData
方法会被调用,并且接收到子组件传递的数据 data
,将其赋值给 receivedData
,从而在模板中展示出来。
通过 props
和自定义事件,父子组件之间可以实现高效、灵活的通信,这对于构建复杂的 Vue 应用至关重要。
希望这篇关于父子组件通信的文章能帮助你更好地理解和运用 Vue 组件间的交互。如果你觉得文章有用,欢迎点赞、收藏、关注,并在评论区分享你的见解和疑问,我们一起交流进步。后续会持续为你带来更多 Vue 相关的精彩内容。