功能需求
- 超出内容区域宽度显示tooltip
- 自定义tooltip内容
- tooltip位置跟随鼠标位置显示
组件源码
<template>
<el-tooltip
v-bind="$attrs"
:popper-class="['ts-ellipsis-tooltip', popperClass]"
:placement="tooltipPlacement"
:disabled="disabled"
:offset="tooltipOffset"
>
<template #content>
<slot v-if="$slots.content" name="content" />
<template v-else>
{{ content || text }}
</template>
</template>
<div :class="['ts-ellipsis', { 'cursor-default': !disabled && placement === 'mouse' }, textClass]" @mouseover="handleMouseover">
<span :ref="uniqueRefName">{{ text }}</span>
</div>
</el-tooltip>
</template>
<script>
import { uniqueId } from 'lodash';
export default {
props: {
text: {
type: String,
default: ''
},
content: {
type: String,
default: ''
},
offset: {
type: String,
default: ''
},
placement: {
type: String,
default: ''
},
popperClass: {
type: String,
default: ''
},
textClass: {
type: String,
default: ''
},
refName: {
type: String,
default: ''
}
},
data() {
return {
uniqueRefName: '',
disabled: true,
tooltipPlacement: this.placement,
tooltipOffset: this.offset
};
},
created() {
this.uniqueRefName = this.refName || uniqueId('ellipsis-');
},
methods: {
handleMouseover({ offsetX }) {
const contentRef = this.$refs[this.uniqueRefName];
const parentWidth = contentRef.parentNode.offsetWidth;
const contentWidth = contentRef.offsetWidth;
if (this.placement === 'mouse') {
this.tooltipPlacement = 'bottom-start';
this.tooltipOffset = offsetX + 5;
}
this.disabled = contentWidth <= parentWidth;
},
}
};
</script>
<style lang="scss" scoped>
.ts-ellipsis {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
&.cursor-default {
cursor: default;
}
}
</style>
组件调用
<ts-ellipsis-tooltip
popper-class="my-ellipsis-tooltip"
text="这是显示文本"
effect="light"
placement="mouse"
:open-delay="1"
>
<template #content>
这是tooltip内容
</template>
</ts-ellipsis-tooltip>