当前位置:首页 > VUE

vue实现slot

2026-03-07 07:53:20VUE

Vue 插槽(Slot)的实现

Vue 的插槽(Slot)是一种组件间内容分发的机制,允许父组件向子组件传递模板片段。插槽分为默认插槽、具名插槽和作用域插槽三种类型。

默认插槽

默认插槽是最基础的插槽形式,子组件通过 <slot> 标签定义插槽位置,父组件可以在子组件标签内部传递内容。

子组件定义:

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

父组件使用:

<template>
  <ChildComponent>
    <p>这是插入到子组件的内容</p>
  </ChildComponent>
</template>

具名插槽

具名插槽允许定义多个插槽,通过 name 属性区分不同插槽。

子组件定义:

vue实现slot

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

父组件使用:

<template>
  <ChildComponent>
    <template v-slot:header>
      <h1>这是头部内容</h1>
    </template>
    <p>这是默认插槽内容</p>
    <template v-slot:footer>
      <p>这是底部内容</p>
    </template>
  </ChildComponent>
</template>

作用域插槽

作用域插槽允许子组件向父组件传递数据,父组件可以自定义渲染逻辑。

子组件定义:

<template>
  <div>
    <slot :item="item" :index="index"></slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      item: '子组件数据',
      index: 1
    }
  }
}
</script>

父组件使用:

vue实现slot

<template>
  <ChildComponent>
    <template v-slot:default="slotProps">
      <p>接收到的数据: {{ slotProps.item }}, 索引: {{ slotProps.index }}</p>
    </template>
  </ChildComponent>
</template>

动态插槽名

Vue 2.6.0+ 支持动态插槽名,通过方括号语法实现。

父组件使用:

<template>
  <ChildComponent>
    <template v-slot:[dynamicSlotName]>
      <p>动态插槽内容</p>
    </template>
  </ChildComponent>
</template>

<script>
export default {
  data() {
    return {
      dynamicSlotName: 'header'
    }
  }
}
</script>

缩写语法

Vue 提供了插槽的缩写语法,v-slot: 可以简写为 #

父组件使用:

<template>
  <ChildComponent>
    <template #header>
      <h1>缩写语法头部内容</h1>
    </template>
  </ChildComponent>
</template>

插槽机制为 Vue 组件提供了灵活的内容分发能力,通过合理使用可以构建高度可复用的组件结构。

标签: vueslot
分享给朋友:

相关文章

vue实现贴图

vue实现贴图

Vue 实现贴图功能 在Vue中实现贴图功能通常涉及将图片动态添加到指定位置或元素上。以下是几种常见实现方式: 使用v-bind动态绑定图片 通过数据驱动的方式动态更换图片源: <templ…

vue实现主页

vue实现主页

Vue 实现主页的基本步骤 创建一个 Vue 主页通常涉及以下几个关键步骤,从项目初始化到页面布局和功能实现。 初始化 Vue 项目 使用 Vue CLI 或 Vite 初始化项目。Vue CLI…

vue实现 单选

vue实现 单选

实现 Vue 单选功能 在 Vue 中实现单选功能可以通过多种方式完成,以下是几种常见的方法: 使用 v-model 绑定单选按钮 通过 v-model 可以轻松实现单选功能,将单选按钮的值绑定到同…

vue实现treeview

vue实现treeview

Vue 实现 TreeView 的方法 使用递归组件实现 TreeView 递归组件是 Vue 中实现 TreeView 的常见方式。通过组件调用自身,可以轻松处理嵌套的树形结构数据。 <te…

vue 实现赋值

vue 实现赋值

Vue 实现赋值的方法 在 Vue 中,赋值操作通常涉及数据绑定和响应式更新。以下是几种常见的赋值方式: 直接赋值给 data 属性 在 Vue 实例的 data 对象中定义的属性可以直接通过 th…

vue实现表单

vue实现表单

Vue 表单实现方法 双向数据绑定 使用 v-model 指令实现表单元素与数据的双向绑定。适用于 input、textarea、select 等元素。 <template> <…