当前位置:首页 > VUE

vue slot实现

2026-01-07 17:39:02VUE

vue slot 的实现方法

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

默认 slot

默认 slot 是最基础的 slot 使用方式,父组件可以在子组件标签内插入任意内容,这些内容会替换子组件中的 <slot> 标签。

子组件代码:

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

父组件代码:

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

具名 slot

具名 slot 允许父组件将内容插入到子组件的特定位置,通过 name 属性来标识不同的 slot。

子组件代码:

vue slot实现

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

父组件代码:

<template>
  <child-component>
    <template v-slot:header>
      <h1>自定义头部</h1>
    </template>
    <p>默认 slot 内容</p>
    <template v-slot:footer>
      <p>自定义底部</p>
    </template>
  </child-component>
</template>

作用域 slot

作用域 slot 允许子组件将数据传递给父组件,父组件可以使用这些数据来渲染内容。

子组件代码:

<template>
  <div>
    <slot :user="user"></slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      user: {
        name: '张三',
        age: 25
      }
    }
  }
}
</script>

父组件代码:

vue slot实现

<template>
  <child-component>
    <template v-slot:default="slotProps">
      <p>用户名: {{ slotProps.user.name }}</p>
      <p>年龄: {{ slotProps.user.age }}</p>
    </template>
  </child-component>
</template>

动态 slot 名

动态 slot 名允许通过变量动态指定 slot 名称,增加灵活性。

父组件代码:

<template>
  <child-component>
    <template v-slot:[dynamicSlotName]>
      <p>动态 slot 内容</p>
    </template>
  </child-component>
</template>

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

slot 缩写语法

Vue 提供了 v-slot 的缩写语法,可以用 # 代替 v-slot:

父组件代码:

<template>
  <child-component>
    <template #header>
      <h1>缩写语法头部</h1>
    </template>
  </child-component>
</template>

以上方法涵盖了 Vue slot 的主要使用场景,可以根据实际需求选择合适的方式来实现内容分发。

标签: vueslot
分享给朋友:

相关文章

vue实现上移下移插件

vue实现上移下移插件

实现上移下移功能的 Vue 插件 在 Vue 中实现列表项的上移和下移功能,可以通过自定义指令或组件封装的方式完成。以下是两种常见实现方式: 基于数组操作的通用方法 通过操作数组索引实现元素位置交换…

vue实现erp

vue实现erp

Vue实现ERP系统的关键步骤 技术选型与架构设计 采用Vue 3 + TypeScript构建前端,搭配Pinia状态管理,Element Plus或Ant Design Vue作为UI框架。后端可…

vue实现 toast

vue实现 toast

Vue 实现 Toast 组件 在 Vue 中实现 Toast 组件可以通过多种方式完成,以下是几种常见的方法: 使用全局组件和事件总线 创建一个全局的 Toast 组件,并通过事件总线或 Vue…

vue实现海报

vue实现海报

Vue 实现海报生成方案 使用 html2canvas 库 html2canvas 是一个将 HTML 元素转换为 Canvas 的库,适合将 Vue 组件渲染为海报图片 安装依赖: npm in…

vue实现picker

vue实现picker

Vue 实现 Picker 组件的方法 在 Vue 中实现 Picker 组件可以通过多种方式完成,以下是几种常见的实现方法: 使用原生 HTML 和 CSS 实现 通过 Vue 的模板和样式绑定…

vue 实现筛选

vue 实现筛选

实现筛选功能的基本方法 在Vue中实现筛选功能通常涉及以下几个核心步骤: 数据绑定与筛选逻辑 使用v-model绑定筛选条件到Vue实例的数据属性,结合计算属性实现动态筛选: data() {…