您的位置:首页 > Web前端 > Vue.js

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

2021-03-13 12:02 537 查看

插槽内容使用方法介绍

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

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#%E6%8F%92%E6%A7%BD%E5%86%85%E5%AE%B9

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: