第十八节——插槽

概念

在Vue中,插槽(Slots)是一种用于组件模板中的特殊语法,用于实现组件的内容分发和复用。插槽允许父组件在子组件的模板中插入任意的内容,从而实现更灵活的组件组合和定制

默认插槽(Default Slot)

默认插槽是最常用的插槽类型。在子组件的模板中,使用<slot></slot>标签定义默认插槽的位置。父组件在使用子组件时,可以在子组件的标签内放置内容,这些内容将被插入到子组件模板中的默认插槽位置

父组件

复制代码
<template>
  <div>
    <LearnSlot2>
      任意内容
    </LearnSlot2>
  </div>
</template>

<script>
import LearnSlot2 from "./learn-slot2.vue";

export default {
  components: {
    LearnSlot2,
  },
};
</script>

子组件

复制代码
<template>
  <div>
    <slot></slot>
  </div>
</template>

具名插槽(Named Slots)

除了默认插槽,Vue还支持具名插槽。具名插槽允许在子组件中定义多个命名插槽,父组件可以根据插槽的名称来插入内容。在子组件的模板中,使用<slot name="slotName"></slot>标签定义具名插槽的位置,并为每个插槽指定一个唯一的名称。在父组件使用子组件时,使用具名插槽的语法来插入相应名称的内容。

父组件

复制代码
<template>
  <div>
    <LearnSlot2>
      <!-- <h1>一级标题</h1> -->
      <!-- 
        # 后面是插槽的名字
       -->
      <template #footer>
        <div>底部</div>
      </template>
      <template #header>
        <div>头部</div>
      </template>
      <template #content>
        <div>内容</div>
      </template>
    </LearnSlot2>
  </div>
</template>

<script>
import LearnSlot2 from "./learn-slot2.vue";

export default {
  components: {
    LearnSlot2,
  },
};
</script>

子组件

复制代码
<template>
  <div>
    一个组件
    <!-- 
      使用slot这个组件展示
      组件标签中间的内容
     -->
    <!-- 
      使用name跟上插槽的名字
      -->
    <slot name="header"></slot>
    <slot name="content"></slot>
    <slot name="footer"></slot>
  </div>
</template>

作用域插槽(Scoped Slots)

作用域插槽是一种特殊的插槽类型,它允许slot组件向子组件传递数据,并且子组件可以在插槽中使用该数据进行渲染。

父组件

复制代码
<!-- ParentComponent.vue -->
<template>
  <div>
    <h1>Parent Component</h1>
    <ListComponent>
      <!-- 使用作用域插槽来渲染列表项 -->
      <template v-slot="{ item }">
        <li>{{ item.name }}</li>
      </template>
    </ListComponent>
  </div>
</template>

<script>
import ListComponent from './ListComponent.vue';

export default {
  components: {
    ListComponent
  }
}
</script>

子组件

复制代码
<!-- ListComponent.vue -->
<template>
  <div>
    <h2>List Component</h2>
    <ul>
      <slot v-for="item in items" :item="item" :key="item.id"></slot>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' },
        { id: 3, name: 'Item 3' }
      ]
    };
  }
}
</script>
相关推荐
麦麦大数据8 分钟前
F024 CNN+vue+flask电影推荐系统vue+python+mysql+CNN实现
vue.js·python·cnn·flask·推荐算法
white-persist14 分钟前
JWT 漏洞全解析:从原理到实战
前端·网络·python·安全·web安全·网络安全·系统安全
果粒chenl35 分钟前
React学习(四) --- Redux
javascript·学习·react.js
IT_陈寒44 分钟前
React 性能优化:5个实战技巧让首屏加载提升50%,开发者亲测有效!
前端·人工智能·后端
rising start1 小时前
前端基础一、HTML5
前端·html·html5
Never_Satisfied1 小时前
在JavaScript / HTML中,div容器在内容过多时不显示超出的部分
开发语言·javascript·html
鬼谷中妖1 小时前
JavaScript 循环与对象:深入理解 for、for...in、for...of、不可枚举属性与可迭代对象
前端
大厂码农老A1 小时前
你打的日志,正在拖垮你的系统:从P4小白到P7专家都是怎么打日志的?
java·前端·后端
im_AMBER1 小时前
CSS 01【基础语法学习】
前端·css·笔记·学习
DokiDoki之父1 小时前
前端速通—CSS篇
前端·css