vue3文本超出三行显示省略号,点击查看更多显示全部文本
只有一行时(不显示展开按钮):
话不多说,上码
~template
<el-col :span="24"><el-form-item :label="$t('warningOrgNames_')"><div class="content-box" ref="contanierRef"><div ref="contentRef" id="content" :class="isExpanded ? 'text-expanded' : 'text-ellipsis'">{{ form.informInstitution }}</div><div class="show-more" v-if="shouldShowMore" @click="showMore">{{isExpanded ? '收起' : '查看更多'}}</div></div></el-form-item></el-col>
~js
import { ref, reactive, watch, nextTick } from "vue";const contentRef = ref(null);const isExpanded = ref(false); // 默认不展开const shouldShowMore = ref(false); // 是否显示查看更多按钮const contentMaxHeight = ref(0); // 内容的最大高度// 查看更多按钮逻辑const showMore = () => {isExpanded.value = !isExpanded.value;};// 检查元素是否溢出 - 注意,这里不能在onMounted函数进行(会在父组件先组件挂载),还拿不到弹窗里的节点const checkOverflow = async() => {await nextTick();if (contentRef.value) {// 元素内部所有滚动内容的总高度const contentHeight = contentRef.value.scrollHeight;// 计算行高const lineHeight = parseInt(window.getComputedStyle(contentRef.value).lineHeight);const maxLines = 3;// 3行的行高contentMaxHeight.value = lineHeight * maxLines;shouldShowMore.value = contentHeight > contentMaxHeight.value;}
};// 打开弹窗 -- 可通过接收参数data来展示父组件的数据
const openDialog = async (row, data, requestFn) => {visible.value = true;try {...// 需要在打开弹窗获取到数据时才检查文本高度
++ checkOverflow()}...
}// 点击查看更多/收起按钮时也触发检查一下文本高度
++ watch(isExpanded, (val) => {
++ checkOverflow();
++ })// 关闭
const handleCancel = () => {...// 关闭按钮时重置一下展开按钮
++ isExpanded.value = false;visible.value = false;
};
~style
.content-box {position: relative;
}
.text-ellipsis {display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 3; /* 限制文本显示为3行 */line-height: 2.5;overflow: hidden;
}
.show-more {position: absolute;color: #409EFF;cursor: pointer;right: 0;bottom: -20px;
}
.text-expanded {-webkit-line-clamp: unset; /* 取消限制 */
}
由于这是封装后的组件,不能在onMounted函数判断元素是否溢出,要在打开弹窗获取到数据时才调用checkOverflow()