vue添加插槽
时间: 2025-04-29 17:47:22 浏览: 22
<<
在 Vue.js 中,插槽(slot)是强大的组件功能之一,它可以让你将自定义内容注入到另一个组件中。以下是几种类型的插槽及如何使用它们:
### 默认插槽
这是最基础的一种形式,默认插槽让父组件向子组件传递内容。
```html
<!-- 子组件 -->
<template>
<div class="child-component">
<!-- 插槽的位置 -->
<slot></slot>
</div>
</template>
<!-- 父组件使用时 -->
<ChildComponent>默认插槽的内容。</ChildComponent>
```
### 命名插槽
当有多个位置要插入不同内容时,则需用命名插槽区分每个部分。
```html
<!-- 子组件 -->
<template>
<header><slot name="header"></slot></header>
<main><slot></slot></main>
<footer><slot name="footer"></slot></footer>
</template>
<!-- 使用时指定具名插槽 -->
<ChildComponent>
<template v-slot:header>
这里是要放在头部的内容。
</template>
主体部分内容
<template #footer>
底部区域的信息。
</template>
</ChildComponent>
```
注意:`v-slot:` 可简写为 `#`.
### 作用域插槽
有时我们需要从子组件内传数据给父级提供的插槽模板,这就是所谓的作用域插槽。
```html
// 子组件
<template>
<ul>
<li v-for="item in items" :key="item.id"><slot :text="item.text"/></li>
</ul>
</template>
<script setup lang='ts'>
import { ref } from 'vue';
const items = [
{ id:0, text:'Item A' },
{ id:1, text:'Item B' }
];
</script>
// 在父组件调用时获取并利用这些信息
<MyListComponent>
<template v-slot:default="{ text }">{{ text }}</template>
</MyListComponent>
```
阅读全文
相关推荐


















