VUE3组件封装代码
<template>
<a-tooltip @mouseenter="showToolTip" v-bind="getBindValue">
<template #title>
{{ props.title }}
</template>
<slot><span>{{ props.title }}</span></slot>
</a-tooltip>
</template>
<script setup>
import {defineProps,computed,useAttrs} from "vue";
const props = defineProps({
title:{
type:String,
default:''
}
})
const getBindValue = computed(() => {
const delArr = ['title']
const attrs = useAttrs()
const obj = { ...attrs, ...props }
for (const key in obj) {
if (delArr.indexOf(key) !== -1) {
delete obj[key]
}
}
return obj
})
const showToolTip = (e) => {
const {clientWidth,scrollWidth} = e.target
if (clientWidth >= scrollWidth) {
e.target.style.pointerEvents = "none";
}
}
</script>
<style scoped>
</style>
VUE3使用
<template>
<ToolTip :title="text" placement="topLeft">
<span class="text">{{text}}</span>
</ToolTip>
</template>
<style>
span.text{
display: inline-block;
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space:nowrap;
}
</style>
VUE2组件封装代码
<template>
<a-tooltip @mouseenter="showToolTip" v-bind="getBindValue">
<template #title>
{{ title }}
</template>
<slot><span class="text" :style="{maxWidth:maxWidth}">{{ title }}</span></slot>
</a-tooltip>
</template>
<script>
export default {
name: "ToolTip",
props: {
title:{
type:String,
default:''
},
maxWidth:{
type:String,
default: '100%'
}
},
computed:{
getBindValue(){
const delArr = ['title','maxWidth']
const attrs = this.$attrs
const obj = { ...attrs, ...this.$props }
for (const key in obj) {
if (delArr.indexOf(key) !== -1) {
delete obj[key]
}
}
return obj
}
},
methods:{
showToolTip(e) {
const {clientWidth,scrollWidth} = e.target
if (clientWidth >= scrollWidth) {
e.target.style.pointerEvents = "none";
}
}
}
}
</script>
<style scoped>
span.text{
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
VUE2使用
<ToolTip :title="text" placement="topLeft" />