Vue中的插槽Slot的使用说明

Vue.js 的插槽(Slot)是一种强大的功能,它允许你在父组件中定义可重用的模板,并在子组件中插入自定义内容。以下是关于 Vue 中插槽的详细使用说明和代码示例:

使用说明:

  1. 默认插槽:你可以在子组件中定义一个名为 "default" 的插槽。这是最常见的插槽类型。
  2. 具名插槽:你也可以定义具名插槽,这样你就可以在父组件中为每个插槽提供特定的内容。
  3. 作用域插槽 :在子组件中,你可以使用 v-slot 指令来定义一个作用域插槽,这个插槽可以访问子组件的数据。

代码示例:

默认插槽

子组件(ChildComponent.vue):

复制代码
`<template>
<div>
<h1>Child Component</h1>
<slot></slot> <!-- 默认插槽 -->
</div>
</template>`

父组件(ParentComponent.vue):

复制代码
`<template>
<ChildComponent>
<p>This is some content inside the Child Component.</p>
</ChildComponent>
</template>`

具名插槽

子组件(WithNamedSlots.vue):

复制代码
`<template>
<div>
<h1>Named Slots</h1>
<slot name="header"></slot> <!-- 具名插槽 -->
<slot name="footer"></slot> <!-- 具名插槽 -->
</div>
</template>`

父组件(UsingNamedSlots.vue):

复制代码
`<template>
<WithNamedSlots>
<template v-slot:header>
<h2>This is the header content.</h2>
</template>
<template v-slot:footer>
<p>This is the footer content.</p>
</template>
</WithNamedSlots>
</template>`

作用域插槽

子组件(WithScopedSlots.vue):

复制代码
`<template>
<div>
<h1>{``{ message }}</h1> <!-- 访问子组件数据 -->
<slot :message="message"></slot> <!-- 作用域插槽 -->
</div>
</template>
<script>
export default {
data() {
return { message: 'Hello from Child Component!' }; // 子组件数据
}
}
</script>`

父组件(UsingScopedSlots.vue):

复制代码
`<template>
<WithScopedSlots>
<template v-slot:default="{ message }"> <!-- 访问作用域插槽的数据 -->
<p>{``{ message }}</p> <!-- 使用作用域插槽的数据 -->
</template>
</WithScopedSlots>
</template>`
相关推荐
lecepin1 小时前
AI Coding 资讯 2025-09-17
前端·javascript·面试
IT_陈寒1 小时前
React 18实战:7个被低估的Hooks技巧让你的开发效率提升50%
前端·人工智能·后端
树上有只程序猿2 小时前
终于有人把数据库讲明白了
前端
猩兵哥哥2 小时前
前端面向对象设计原则运用 - 策略模式
前端·javascript·vue.js
司宸2 小时前
Prompt设计实战指南:三大模板与进阶技巧
前端
RoyLin2 小时前
TypeScript设计模式:抽象工厂模式
前端·后端·typescript
华仔啊2 小时前
Vue3+CSS 实现的 3D 卡片动画,让你的网页瞬间高大上
前端·css
江城开朗的豌豆2 小时前
解密React虚拟DOM:我的高效渲染秘诀 🚀
前端·javascript·react.js
vivo互联网技术2 小时前
拥抱新一代 Web 3D 引擎,Three.js 项目快速升级 Galacean 指南
前端·three.js