这类功能很常见,其实之前也写过,今天特意整理出来分享给大家,我这里分装成一个组件,大家有需要的可以复制即用。
完整代码:
<template>
<div ref="textExpand">
<div v-if="!(showPopover && showPopoverJudge)">
<span :style="expandStyle">
{{ text === null || text === undefined || text === '' ? '--' : text }}
</span>
<div >
<span v-if="showBtn && showBtnJudge">
<span v-if="!showFull" @click.stop="showFullFn(true)">
展开
<i v-if="showBtnIcon" />
</span>
<span v-else @click.stop="showFullFn(false)">
收起
<i v-if="showBtnIcon" />
</span>
</span>
</div>
</div>
<el-popover v-else :placement="popoverPlace" trigger="hover">
<div >
{{ text }}
</div>
<span :style="expandStyle" slot="reference">{{ text }}</span>
</el-popover>
</div>
</template>
<script>
export default {
props: {
text: {
// 文本内容
type: String,
default: () => '',
},
expand: {
// 折叠显示行数
type: Number,
default: () => 3,
},
showBtn: {
// 展开、折叠按钮
type: Boolean,
default: true,
},
showBtnIcon: {
// 展开、折叠 icon
type: Boolean,
default: true,
},
showPopover: {
// popover 显示全文本
type: Boolean,
default: false,
},
popoverPlace: {
// popover 位置
type: String,
default: 'bottom',
},
},
data() {
return {
showFull: false, // 是否展示全文本
expandStyle: '',
showBtnJudge: false, // 判断是否需要折叠展示按钮
showPopoverJudge: false, // 判断是否需要折叠展示 popover
};
},
watch: {
text: function () {
this.textExpand();
},
},
mounted() {
this.textExpand();
},
methods: {
showFullFn(value) {
this.expandStyle = value
? ''
: `display: -webkit-box;word-break: break-all;-webkit-line-clamp: ${this.expand};-webkit-box-orient: vertical;text-overflow: ellipsis;overflow: hidden;`;
this.showFull = value;
},
textExpand() {
// 判断是否需要折叠
this.$nextTick(() => {
const { expand } = this;
const textExpandStyle = window.getComputedStyle(this.$refs.textExpand);
const textExpandHeight = parseFloat(textExpandStyle.height); //获取总高度
const textExpandLineHeight = parseFloat(textExpandStyle.lineHeight); //获取行高
// 计算行高
const rects = Math.ceil(textExpandHeight / textExpandLineHeight);
if (rects <= expand) {
// 不需要折叠展示
this.showBtnJudge = false;
this.showPopoverJudge = false;
} else {
this.showBtnJudge = true;
this.showPopoverJudge = true;
this.expandStyle = `display: -webkit-box;word-break: break-all;-webkit-line-clamp: ${this.expand};-webkit-box-orient: vertical;text-overflow: ellipsis;overflow: hidden;`;
}
});
},
},
};
</script>
<style lang="less" scoped>
.text-expand {
&-content {
word-break: break-all;
white-space: pre-wrap;
}
.expander {
text-align: right;
.action {
display: inline-block;
font-size: 14px;
color: #0281f0;
cursor: pointer;
i {
display: inline;
font-size: 12px;
}
}
.action.action-pack {
margin-left: 0;
}
}
}
.popover-content {
max-width: 40vw;
max-height: 30vh;
overflow: hidden;
overflow-y: auto;
word-break: break-all;
}
</style>
总结
以上就是今天要分享的内容,本文仅仅简单介绍了平常工作中常见的需求,同一种需求不同状态下写,代码也会不一样,写文章也是为了更好的总结,从中慢慢积累经验。