vue3 elementplus 封装el-tooltip
基于父元素的宽度计算是否需要展示el-tooltip
<template> <el-tooltip class="item" :effect="effect" :content="content" placement="top-start" :disabled="showPopper"> <slot /> </el-tooltip> </template> <script setup> import { defineOptions, getCurrentInstance, onBeforeUnmount, onMounted, ref } from 'vue' defineOptions({ name: 'CustomTooltip' }) defineProps({ effect: { type: String, default: 'dark' }, content: String, openDelay: { type: Number, default: 0 } }) const currentInstance = getCurrentInstance() const showPopper = ref(false) const el = () => { return currentInstance.proxy.$el } const handleShowPopper = () => { const { clientWidth, scrollWidth } = el().nextElementSibling if (scrollWidth <= clientWidth) { showPopper.value = true } else { showPopper.value = false } } const on = (element, event, handler) => { if (element && event && handler) { element.addEventListener(event, handler, false) } } const off = (element, event, handler) => { if (element && event) { element.removeEventListener(event, handler, false) } } onMounted(() => { handleShowPopper() on(el()?.nextElementSibling, 'mouseenter', handleShowPopper) }) onBeforeUnmount(() => { const reference = el().nextElementSibling off(reference, 'mouseenter', handleShowPopper) }) </script>
用法:
<CustomTooltip content="这是内容" effect="dark"> <span>这是内容</span> </CustomTooltip>