Vue 插槽之插槽内容学习总结

插槽内容使用方法介绍

父组件中引用支持插槽内容的子组件,形如以下(假设子组件为NavigationLink.vue)

<navigation-link url="/profile">
  Your Profile
</navigation-link>

然后在子组件<template> 模板中使用<slot></slot>,形如以下:

<a
  v-bind:href="url"
  class="nav-link"
>
  <slot></slot>
</a>

这样以后,当组件渲染的时候,子组件中的<slot></slot> 将会被替换为父组件模板中,子组件起始标签和结束标签之间的内容--这里称之为“插槽内容”。

插槽内可以包含任何模板代码,包括 HTML:

<navigation-link url="/profile">
  <!-- 添加一个 Font Awesome 图标 -->
  <span class="fa fa-user"></span>
  Your Profile
</navigation-link>

甚至其它的组件:

<navigation-link url="/profile">
  <!-- 添加一个图标的组件 -->
  <font-awesome-icon name="user"></font-awesome-icon>
  Your Profile
</navigation-link>

如果子组件 template没有包含一个 <slot> 元素,则父组件中,该组件起始标签和结束标签之间的任何内容都会被抛弃

应用举例

需求描述

自定义卡片组件,用于展示不同的内容,形式为 显示卡片标题和内容,卡片和卡片之间看起来需要有“分界条”

Testpage.vue

<template>
  <div class="page-main">
    <div class="main-content">
      <card class="authors-single" title="测试标签1">
        <div style="height:50px;width:60px">hello</div>
      </card>
      <card class="authors-single" title="测试标签2">
          <div>卡片内容</div>
      </card>
    </div>
  </div>
</template>

<script>
import Card from "@/components/Card";

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

<style scoped lang="scss">
.page-main {
  height: calc(100vh - 129px);
  padding: 10px 10px;
  display: flex;
  flex-direction: column;
  .main-content {
    overflow: auto;
    flex: auto;
  }
}
</style>

Card.vue

组件路径位于@/components/Card/Card.vue

<template>
  <div class="card">
    <div class="card-title">{{title}}</div>
    <div class="card-content">
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    title: {
      type: String
    }
  }
}
</script>

<style lang="scss" scoped>
.card {
  display: flex;
  flex-direction: column;
  padding: 2px 5px;

  &-title {
    flex: none;
    padding: 0.4em 8px;
    font-size: 17px;
    position: relative;
    background-color: #f8f8f8;

    &::before {
      content: "";
      width: 4px;
      height: 100%;
      background: #59bcc7;
      position: absolute;
      top: 0;
      left: 0;
    }
  }

  &-content {
    flex: auto;
    padding: 10px;
    margin-top: 10px;
    background-color: #f8f8f8;
  }
}
</style>

效果

参考连接

https://cn.vuejs.org/v2/guide/components-slots.html#插槽内容

posted @   授客  阅读(709)  评论(0编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
历史上的今天:
2020-03-13 测试思想-流程规范 用例优先级定义与使用规范 V1.0
点击右上角即可分享
微信分享提示