在封装自定义组件时,需要判断使用者是否使用了插槽<slot="aaa">,如果没有则使用一个组件中默认的值,反之就用传入的内容<template name="aaa"></template>,实现如下:
<div class="line"><div class="line-title"><div class="left"><slot name="title"></slot></div><div class="right" v-if="hasButton"><slot name="button"></slot></div><div class="right" v-else>导出 <i class="el-icon-upload"></i></div></div><div class="line-charts" :id="chartsId"></div><div class="line-tip"><slot name="tip"></slot></div></div>export default {name: "lineComp",components: {},props: {chartsId: {type: String,default: "",},},computed: {hasButton() {return this.$slots.button !== undefined;}, // 主要看这一部分即可},
}<style lang="scss" scoped>
.line {width: 100%;height: 100%;&-title {width: 100%;height: 24px;display: flex;justify-content: space-between;align-items: center;color: #1492ff;letter-spacing: 1px;padding: 20px 0;.left {padding-left: 8px;border-left: 4px solid #1492ff;font-weight: bolder;font-size: 18px;}}&-charts {width: 100%;min-height: 500px;}&-tip {}
}
</style>
// 使用:
<lineComp :chartsId="'chartsId'"><template slot="title"> 测站 </template><template slot="button"> 内容 </template>
</lineComp>