首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Vue 插槽之插槽内容学习总结

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

作者头像
授客
发布2021-03-16 14:57:37
5610
发布2021-03-16 14:57:37
举报
文章被收录于专栏:授客的专栏授客的专栏

插槽内容使用方法介绍

父组件中引用支持插槽内容的子组件,形如以下(假设子组件为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#插槽内容

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-03-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 插槽内容使用方法介绍
  • 应用举例
  • 需求描述
    • Testpage.vue
      • Card.vue
        • 效果
        • 参考连接
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档