vue卡片组件通过具名插槽实现header/footer自定义,支持默认内容回退与作用域插槽传参,结合defineslots可增强typescript类型提示。

Vue.js 中通过 Slots(插槽) 实现卡片组件的 Header 与 Footer 自定义,是解耦结构与内容、提升组件复用性的常用方式。核心思路是:卡片组件只定义容器和布局,把头部、底部区域留给使用者决定渲染什么内容。
基础单个插槽实现 Header/Footer 替换
在卡片组件中使用 <slot></slot> 占位,默认插槽会接收父组件中所有未命名的内容。但这种方式无法区分 Header 和 Footer —— 所有内容都塞进一个位置。
更合理的方式是使用 具名插槽(Named Slots):
- 在卡片组件(如
Card.vue)模板中,为头部和底部分别定义:<header><slot name="header"></slot></header><footer><slot name="footer"></slot></footer> - 父组件使用时,通过
v-slot:xxx(或简写#xxx)指定内容注入到对应位置:<card><br> <template><h2>我的标题</h2></template><br> <p>这里是卡片主体</p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill8078" title="Wjs Uploading Video"><img src="https://img.php.cn/upload/skill/000/000/081/179185692016044.jpg" alt="Wjs Uploading Video" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/skill8078" title="Wjs Uploading Video" class="overflowclass">Wjs Uploading Video</a> <p class="overflowclass">将一个或多个视频上传至YouTube。当用户想“上传到YouTube”“发YouTube”“批量上传”“upload to YouTube”“post videos to YouTube”或发布到YouTube时使用此技能。</p> </div> <a rel="nofollow" href="/xiazai/skill8078" title="Wjs Uploading Video" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div> <br> <template><button>操作按钮</button></template><br></card>
默认内容 + 插槽回退(Fallback)
当父组件没传 Header 或 Footer 时,可提供默认文案或结构,避免空白:
- 在
<slot name="header"></slot>内直接写默认内容:<slot name="header"><h3>默认标题</h3></slot> - Vue 会自动判断:若父组件传了
#header,则渲染传入的内容;否则渲染 slot 标签内的默认内容。
作用域插槽传递数据(如动态 Footer 按钮)
如果 Footer 需要访问卡片内部状态(例如 item.id、loading 状态),可用 作用域插槽:
- 在卡片组件中,把数据作为属性传给插槽:
<slot name="footer" :id="itemId" :loading="isLoading"></slot> - 父组件使用时解构接收:
<template id loading><br> <button :disabled="loading">删除 {{ id }}</button><br></template>
组合式 API 中的插槽类型提示(TypeScript 友好)
使用 defineSlots 可为插槽提供类型声明,提升开发体验:
- 在
Card.vue的<script setup></script>中添加:defineSlots header: (props: { title?: string }) => any,<br> footer: (props: { disabled?: boolean }) => any<br>(); - 这样在父组件使用
#header时,IDE 就能提示 props 参数类型。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










