当前位置:首页 > 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实现markdown

vue实现markdown

Vue 实现 Markdown 编辑器 在 Vue 中实现 Markdown 编辑器可以通过集成第三方库或自定义解析器完成。以下是两种常见方法: 使用第三方库(如 marked 或 markdown…

vue 实现轮播

vue 实现轮播

Vue 实现轮播的方法 使用第三方库(如 Swiper) 安装 Swiper 库: npm install swiper 在 Vue 组件中引入 Swiper: <template&…

vue 实现全屏

vue 实现全屏

Vue 实现全屏功能 在 Vue 中实现全屏功能可以通过浏览器提供的 Fullscreen API 完成。以下是一个完整的实现方案: 安装依赖(可选) 如果需要跨浏览器兼容性更好,可以安装…

实现vue cli

实现vue cli

安装 Vue CLI 确保系统中已安装 Node.js(版本建议 12.x 或更高)。通过 npm 全局安装 Vue CLI: npm install -g @vue/cli 安装完成后验证版本:…

vue简单实现

vue简单实现

Vue 简单实现示例 以下是一个使用 Vue.js 创建简单应用的示例,涵盖基本功能如数据绑定、事件处理和组件化。 基础 HTML 结构 <!DOCTYPE html> <ht…

vue实现动态禁用

vue实现动态禁用

动态禁用表单元素或按钮 在Vue中实现动态禁用功能通常通过v-bind:disabled(或简写为:disabled)绑定一个响应式变量实现。当变量值为true时,元素被禁用;为false时启用。…