深入理解 Vue.js 中的 Props、Emits 和 Slots

使用 Props 实现组件通信

ts 复制代码
const props = defineProps<{
  mode: "create" | "update";
  title?: string;
  content?: string;
}>();

Props 是父组件向子组件传递数据的桥梁。在此例中,mode 是必填字段,仅限于 "create""update",而 titlecontent 是可选的字符串类型。

通过 Emits 同步数据更新

ts 复制代码
const emit = defineEmits(["update:title", "update:content"]);

Emits 允许子组件向父组件发送事件以通知数据变化。这里定义了 update:titleupdate:content 事件,用于更新父组件的数据。

Props、Emits 与 v-model 的双向绑定简化

ts 复制代码
<Write
    mode="create"
    v-model:title="form.title"
    v-model:content="form.content"
/>

对于 numberstring 等基本数据类型,赋值是深拷贝 。子组件中对 titlecontent 的修改不会直接影响父组件的值,因此需要通过 emit 来同步更新。好在 v-model 提供了语法糖,自动绑定到 update:titleupdate: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 渲染了父组件定义的一组按钮,在不改变子组件核心结构的前提下增强了灵活性。

相关推荐
chQHk57BN3 分钟前
PWA开发指南:构建可离线使用的渐进式Web应用
前端
weixin_408099679 分钟前
【保姆级教程】按键精灵调用 OCR 文字识别 API(从0到1完整实战 + 可运行脚本)
java·前端·人工智能·后端·ocr·api·按键精灵
xdl259915 分钟前
CSS flex 布局中没有 justify-items
前端·css
百撕可乐15 分钟前
WenDoraAi官网NextJS实战04:HTTP 请求封装与SSR
前端·网络·网络协议·react.js·http
Sestid17 分钟前
前端AI编程使用技巧(后续会更新cursor和claude code for vscode)
前端·vscode·ai编程·claude·cursor
freeWayWalker20 分钟前
Vue通用缩放容器
前端·javascript·vue.js
Hello--_--World28 分钟前
VUE:逻辑复用
前端·javascript·vue.js
陶甜也1 小时前
3D智慧城市:blender建模、骨骼、动画、VUE、threeJs引入渲染,飞行视角,涟漪、人物行走
前端·3d·vue·blender·threejs·模型
患得患失9491 小时前
【前端websocket】企业级功能清单
前端·websocket·网络协议