当前位置:首页 > 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。

子组件代码:

<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>

父组件代码:

<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 的主要使用场景,可以根据实际需求选择合适的方式来实现内容分发。

vue slot实现

标签: vueslot
分享给朋友:

相关文章

vue实现atm

vue实现atm

Vue实现ATM机模拟功能 使用Vue.js实现ATM机模拟功能需要结合组件化开发、状态管理以及用户交互逻辑。以下是关键实现步骤: 核心组件结构 创建以下Vue组件构建ATM界面: Car…

vue实现视频开场

vue实现视频开场

使用 Vue 实现视频开场动画 在 Vue 中实现视频开场动画可以通过结合 HTML5 的 <video> 标签和 Vue 的过渡效果或生命周期钩子来完成。以下是具体实现方法: 安装依…

vue实现安全免登录

vue实现安全免登录

Vue 实现安全免登录的方案 免登录功能通常通过持久化认证状态(如 Token)实现,但需兼顾安全性。以下是基于 Vue 的常见实现方案: 基于 Token 的免登录 登录成功后存储 Toke…

vue按钮实现截屏

vue按钮实现截屏

Vue 按钮实现截屏的方法 在 Vue 项目中实现截屏功能可以通过多种方式完成,以下是几种常见的方法: 使用 html2canvas 库 安装 html2canvas 库: npm insta…

vue状态管理怎么实现

vue状态管理怎么实现

Vue 状态管理实现方法 使用 Vuex(官方推荐) Vuex 是 Vue 的官方状态管理库,适合中大型应用。 安装 Vuex: npm install vuex --save 创建 Store…

vue懒加载实现难吗

vue懒加载实现难吗

vue懒加载的实现难度 Vue懒加载的实现并不复杂,核心逻辑是通过动态导入(Dynamic Imports)和路由配置或组件异步加载完成。以下是具体实现方法: 路由懒加载实现 在Vue Rout…