使用 Props 实现组件通信
ts
const props = defineProps<{
mode: "create" | "update";
title?: string;
content?: string;
}>();
Props
是父组件向子组件传递数据的桥梁。在此例中,mode
是必填字段,仅限于 "create"
或 "update"
,而 title
和 content
是可选的字符串类型。
通过 Emits 同步数据更新
ts
const emit = defineEmits(["update:title", "update:content"]);
Emits
允许子组件向父组件发送事件以通知数据变化。这里定义了 update:title
和 update:content
事件,用于更新父组件的数据。
Props、Emits 与 v-model 的双向绑定简化
ts
<Write
mode="create"
v-model:title="form.title"
v-model:content="form.content"
/>
对于
number
或string
等基本数据类型,赋值是深拷贝 。子组件中对title
或content
的修改不会直接影响父组件的值,因此需要通过emit
来同步更新。好在v-model
提供了语法糖,自动绑定到update:title
和update:content
事件。
子组件需要实现相应的 emit
逻辑:
ts
const emit = defineEmits(["update:title", "update:content"]);
// 同步 title 到父组件
const updateTitle = (e: InputEvent) => {
emit("update:title", (e.target as HTMLInputElement).value);
};
// 同步 content 到父组件
const updateContent = (value: string) => {
emit("update:content", value);
};
通过这种方式,父子组件可以实现数据的双向共享。
对于对象 或数组 ,赋值是浅拷贝 ,子组件的修改会直接反映到父组件,无需
emit
更新。因此,若需共享可变状态,优先传递对象;若仅需只读数据,则传递基本值。
使用 Slots 提升组件灵活性
父组件:自定义插槽内容
ts
<Write mode="create" v-model:title="form.title" v-model:content="form.content">
<template #action>
<div class="flex gap-2">
<a-button type="primary" @click="open = true">保存</a-button>
<a-button type="primary" @click="">保存</a-button>
<a-button type="primary" @click="">保存</a-button>
</div>
</template>
</Write>
子组件:渲染插槽
ts
<div class="flex h-14 items-center justify-between">
<!-- 其他内容 -->
<slot name="action" />
</div>
Slots
允许父组件将自定义内容注入到子组件的特定位置。此例中,命名插槽 action
渲染了父组件定义的一组按钮,在不改变子组件核心结构的前提下增强了灵活性。