当前位置:首页 > VUE

vue实现slot

2026-02-10 08:02:33VUE

Vue 中 Slot 的实现方法

在 Vue 中,slot 是一种内容分发机制,允许父组件向子组件传递模板内容。以下是几种常见的 slot 实现方式:

默认 Slot

默认 slot 是最基础的插槽形式,父组件传递的内容会替换子组件中的 <slot> 标签。

子组件模板:

<div>
  <h2>子组件标题</h2>
  <slot></slot>
</div>

父组件使用:

<child-component>
  <p>这是插入到子组件的内容</p>
</child-component>

具名 Slot

具名 slot 允许父组件针对子组件中不同的 slot 位置分发内容。

子组件模板:

<div>
  <slot name="header"></slot>
  <slot></slot>
  <slot name="footer"></slot>
</div>

父组件使用:

vue实现slot

<child-component>
  <template v-slot:header>
    <h1>页眉内容</h1>
  </template>

  <p>默认 slot 内容</p>

  <template v-slot:footer>
    <p>页脚内容</p>
  </template>
</child-component>

作用域 Slot

作用域 slot 允许子组件将数据传递给父组件中的插槽内容。

子组件模板:

<ul>
  <li v-for="item in items" :key="item.id">
    <slot :item="item"></slot>
  </li>
</ul>

父组件使用:

<child-component>
  <template v-slot:default="slotProps">
    <span>{{ slotProps.item.name }}</span>
  </template>
</child-component>

动态 Slot 名

Vue 2.6.0+ 支持动态 slot 名称。

vue实现slot

父组件使用:

<child-component>
  <template v-slot:[dynamicSlotName]>
    <!-- 内容 -->
  </template>
</child-component>

缩写语法

Vue 提供了简写语法来简化 slot 的使用。

具名 slot 缩写:

<template #header>
  <h1>页眉内容</h1>
</template>

作用域 slot 缩写:

<template #default="{ item }">
  <span>{{ item.name }}</span>
</template>

注意事项

  • 在 Vue 2 中,v-slot 指令只能用在 <template> 上,Vue 3 中可以用在普通元素上
  • 默认 slot 可以使用 v-slot:default 显式声明
  • 作用域 slot 的解构语法与 JavaScript 对象解构类似
  • 动态 slot 名称需要放在方括号中

标签: vueslot
分享给朋友:

相关文章

vue实现横向导航

vue实现横向导航

vue实现横向导航的方法 使用Flex布局实现横向导航 在Vue中可以通过Flex布局快速实现横向导航。创建一个组件,使用display: flex和flex-direction: row属性使导航项…

vue实现radio

vue实现radio

Vue 实现 Radio 按钮 在 Vue 中实现 Radio 按钮可以通过 v-model 进行数据绑定,结合 input 元素的 type="radio" 属性。以下是一个基本示例: <t…

vue 实现上传

vue 实现上传

Vue 实现文件上传 使用 Vue 实现文件上传可以通过原生 HTML 的 <input type="file"> 或第三方库(如 axios、vue-upload-component)完…

vue实现书库

vue实现书库

Vue 实现书库功能 使用 Vue 构建书库功能需要结合前端框架和后端数据管理。以下是实现步骤和关键点: 项目初始化 使用 Vue CLI 或 Vite 初始化项目,安装 Vue Router 和状…

实现简单vue

实现简单vue

实现一个简单的 Vue.js 框架 Vue.js 的核心功能包括数据绑定、响应式系统和虚拟 DOM。以下是一个简化版的 Vue 实现,涵盖基本功能。 数据响应式系统 使用 Object.define…

vue实现投票

vue实现投票

Vue实现投票功能 数据准备 在Vue组件的data中定义投票相关数据,包括选项列表和当前选中状态: data() { return { options: [ { id: 1…