文字溢出组件封装,结合element的tooltip

<template>
	<div class="content-tooltip">
		<el-tooltip placement="top" :disabled="!isShowTooltip" effect="light">
			<template #content>
				<div class="all-content">{
  
  {props.text}}</div>
			</template>
			<div class="ellipsis-text" @mouseenter="visibilityChange($event)">{
  
  { props.text }}</div>
		</el-tooltip>
	</div>
</template>

<script setup>
import { defineProps, ref } from 'vue';

const props = defineProps({
	text: { type: String, required: '' },
});

const isShowTooltip = ref(false);
// 判断是否显示 溢出的文本 el-tooltip
const visibilityChange = (event) => {
	const ev = event.target;
	const evWeight = ev.scrollWidth;
	const contentWeight = ev.clientWidth;
	console.log(ev, evWeight, contentWeight, 1);
	if (evWeight > contentWeight) {
		// 实际宽度 > 可视宽度  文字溢出
		isShowTooltip.value = true;
	} else {
		// 否则为不溢出
		isShowTooltip.value = false;
	}
};
</script>

<style scoped>
.ellipsis-text {
	width: 100%;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	cursor: pointer;
}
.all-content {
	max-width: 600px;
	font-size: 14px;
	white-space: pre-wrap;
}
.content-tooltip {
	overflow: hidden;
	white-space: nowrap;
	text-overflow: ellipsis; /* 溢出显示省略号 */
}
</style>

Vue 2中创建一个基础的文字提示组件Tooltip),可以按照以下步骤进行: 1. 首先,安装依赖: ```bash npm install vue @vue/cli-plugin-component --save ``` 2. 创建一个新的组件文件,例如`Tooltip.vue`: ```html <template> <div class="tooltip"> <button :title="tipText" ref="trigger">点击显示提示</button> <span v-if="showTip" class="tooltip-content">{{ tipText }}</span> </div> </template> <script> export default { name: 'Tooltip', props: { tipText: { type: String, required: true, default: '' }, showTip: { type: Boolean, default: false } }, data() { return { tooltipVisible: false, // 组件内部状态,用于控制提示内容是否显示 }; }, watch: { showTip(newVal) { // 当外部传入的showTip属性改变时更新组件状态 this.tooltipVisible = newVal; } }, methods: { toggleTooltip() { // 显示或隐藏提示 this.showTip = !this.showTip; }, }, mounted() { this.$refs.trigger.addEventListener('mouseover', this.toggleTooltip); // 监听触发事件 this.$refs.trigger.addEventListener('mouseout', () => { this.toggleTooltip(); setTimeout(() => { this.tooltipVisible = false; // 弹出后一段时间自动隐藏 }, 500); }); }, beforeDestroy() { this.$refs.trigger.removeEventListener('mouseover', this.toggleTooltip); this.$refs.trigger.removeEventListener('mouseout', this.toggleTooltip); }, }; </script> <style scoped> .tooltip { position: relative; } .tooltip-content { position: absolute; z-index: 999; background-color: #000; color: #fff; padding: 4px; border-radius: 4px; opacity: 0; transition: opacity 0.3s; } .tooltip:hover .tooltip-content { opacity: 1; } </style> ``` 这个组件接收`tipText`作为提示文字,`showTip`作为是否显示提示的状态,并在鼠标悬停时显示或隐藏提示。当组件销毁时,会移除事件监听。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值