vue自己实现tooltip
自定义 Tooltip 实现方法
使用 Vue 指令实现基础 Tooltip
通过 Vue 自定义指令可以方便地实现 Tooltip 功能。创建一个全局指令,在元素悬停时显示提示信息。
Vue.directive('tooltip', {
bind(el, binding) {
const tooltip = document.createElement('div')
tooltip.className = 'tooltip'
tooltip.textContent = binding.value
document.body.appendChild(tooltip)
el.addEventListener('mouseenter', () => {
const rect = el.getBoundingClientRect()
tooltip.style.display = 'block'
tooltip.style.top = `${rect.top - tooltip.offsetHeight - 5}px`
tooltip.style.left = `${rect.left + rect.width/2 - tooltip.offsetWidth/2}px`
})
el.addEventListener('mouseleave', () => {
tooltip.style.display = 'none'
})
}
})
.tooltip {
position: fixed;
display: none;
background: #333;
color: white;
padding: 5px 10px;
border-radius: 4px;
font-size: 12px;
z-index: 1000;
}
组件化 Tooltip 实现
创建一个可复用的 Tooltip 组件,提供更多自定义选项。
<template>
<div class="tooltip-container">
<slot></slot>
<div
v-if="show"
class="tooltip-content"
:style="{ top: position.top, left: position.left }"
>
{{ content }}
</div>
</div>
</template>
<script>
export default {
props: {
content: String,
placement: {
type: String,
default: 'top'
}
},
data() {
return {
show: false,
position: { top: 0, left: 0 }
}
},
methods: {
updatePosition(el) {
const rect = el.getBoundingClientRect()
switch(this.placement) {
case 'top':
this.position = {
top: `${rect.top - 30}px`,
left: `${rect.left + rect.width/2}px`
}
break
case 'bottom':
this.position = {
top: `${rect.bottom + 5}px`,
left: `${rect.left + rect.width/2}px`
}
break
}
}
},
mounted() {
const el = this.$el.firstElementChild
el.addEventListener('mouseenter', () => {
this.updatePosition(el)
this.show = true
})
el.addEventListener('mouseleave', () => {
this.show = false
})
}
}
</script>
<style>
.tooltip-container {
display: inline-block;
position: relative;
}
.tooltip-content {
position: fixed;
background: #333;
color: white;
padding: 5px 10px;
border-radius: 4px;
transform: translateX(-50%);
z-index: 1000;
}
</style>
添加动画效果
为 Tooltip 添加淡入淡出动画效果,提升用户体验。
<template>
<transition name="fade">
<div
v-if="show"
class="tooltip-content"
:style="{ top: position.top, left: position.left }"
>
{{ content }}
</div>
</transition>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.2s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
支持 HTML 内容
扩展 Tooltip 组件以支持 HTML 内容而不仅仅是纯文本。
<template>
<div v-if="show" class="tooltip-content" v-html="content"></div>
</template>
<script>
export default {
props: {
content: {
type: String,
default: ''
},
allowHtml: {
type: Boolean,
default: false
}
}
}
</script>
这些方法提供了从简单到复杂的 Tooltip 实现方案,可以根据项目需求选择适合的方式或进行组合使用。组件化实现提供了更好的可维护性和扩展性,而指令方式则更加轻量简洁。







