在使用 el-select 时,有时 el-option 的内容过长,导致超长显示,例如:
为了更好展示,我们可以设置一个最大宽度,超出最大宽度时使用省略号代替,当鼠标移入时,使用 el-tooltip 展示完整内容。以下是封装的 ui-tooltip 组件。
<template>
<el-tooltip
:content="content"
:placement="placement"
effect="light"
:disabled="isDisabled"
>
<div class="contentnowrap" @mouseenter="isShowTooltip">
{{ content }}
</div>
</el-tooltip>
</template>
<script>
export default {
name: "UiTooltip",
props: {
content: {
type: String,
default: "",
},
placement: {
type: String,
default: "top",
},
},
data() {
return {
isDisabled: false,
};
},
methods: {
isShowTooltip(e) {
let clientWidth = e.target.clientWidth,
scrollWidth = e.target.scrollWidth;
if (scrollWidth > clientWidth) {
this.isDisabled = false;
} else {
this.isDisabled = true;
}
},
},
};
</script>
<style lang="scss">
.contentnowrap {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
使用方式
1、引入
import UiTooltip from "@/components/ui-tooltip";
2、注册
components: {
UiTooltip,
},
3、使用
<el-select v-model="params.desc" placeholder="请选择" clearable>
<el-option
v-for="(item, index) in list"
:key="index"
:label="item.label"
:value="item.value"
>
<span class="ui-tooltip-item">
<ui-tooltip :content="item.label"></ui-tooltip>
</span>
</el-option>
</el-select>
通过 max-width 设置最大宽度
.ui-tooltip-item {
display: inline-block;
max-width: 150px;
margin-left: 8px;
}
4、效果