当前位置:首页 > 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中实现搜索功能通常涉及以下几个关键步骤,结合数据绑定、计算属性和方法调用来动态过滤和显示结果。 数据绑定与输入处理 使用v-model双向绑定搜索输入框的值,监听用户…

vue设计与实现下载

vue设计与实现下载

vue设计与实现电子书下载 《Vue.js设计与实现》是一本深入解析Vue.js框架原理的书籍,由霍春阳(HcySunYang)撰写。以下是获取该资源的常见途径: 正版购买渠道 京东、当当、天…

vue实现摘要

vue实现摘要

Vue 实现摘要的方法 在 Vue 中实现文本摘要功能通常涉及截取文本的前部分内容并添加省略号。可以通过计算属性、过滤器或自定义指令来实现。 计算属性实现 在 Vue 组件中定义一个计算属性,用于截…

vue聊天实现

vue聊天实现

Vue 聊天应用实现步骤 创建 Vue 项目 使用 Vue CLI 或 Vite 初始化项目,安装必要依赖(如 Vue 3、Element UI 或 Vuetify 用于 UI 组件)。 npm c…

实现vue组件

实现vue组件

Vue 组件的基本实现 Vue 组件是 Vue.js 的核心特性之一,允许将 UI 拆分为独立、可复用的模块。以下是实现 Vue 组件的几种方式: 单文件组件 (SFC) 使用 .vue 文件格式,…

vue observer实现

vue observer实现

Vue Observer 实现原理 Vue 的响应式系统核心是通过 Object.defineProperty(Vue 2)或 Proxy(Vue 3)实现的 Observer 模式。以下是关键实现细…