index.vue 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <template>
  2. <el-tooltip
  3. :content="props.tooltipContent ? props.tooltipContent : props.content"
  4. :placement="props.placement"
  5. :disabled="isShow"
  6. :effect="props.effect"
  7. >
  8. <template #content>
  9. <!-- 此处的默认值先看tooltipContent有没有,没有就给默认content -->
  10. <slot name="tooltipContent">{{ props.tooltipContent ? props.tooltipContent : props.content }}</slot>
  11. </template>
  12. <div class="content" @mouseover="isShowTooltip">
  13. <span ref="contentRef">
  14. <!-- 给一个没有写插槽的默认值,兼容纯文本的情况 -->
  15. <slot name="content">{{ props.content }}</slot>
  16. </span>
  17. </div>
  18. </el-tooltip>
  19. </template>
  20. <script setup lang="ts">
  21. import { ref } from 'vue';
  22. // 使用withDefaults来给props赋默认值
  23. const props = defineProps({
  24. content: {
  25. type: String,
  26. default: '',
  27. },
  28. tooltipContent: {
  29. type: String,
  30. default: '',
  31. },
  32. effect: {
  33. type: String,
  34. default: 'light',
  35. },
  36. placement: {
  37. type: String,
  38. default: 'right',
  39. },
  40. });
  41. // 使用isShow来控制tooltip是否显示
  42. let isShow = ref<boolean>(true);
  43. // 在span标签上定义一个ref
  44. const contentRef = ref();
  45. const isShowTooltip = function (): void {
  46. // 计算span标签的offsetWidth与盒子元素的offsetWidth,给isShow赋值
  47. isShow.value = contentRef.value.parentNode.offsetWidth >= contentRef.value.offsetWidth;
  48. };
  49. </script>
  50. <style>
  51. .content {
  52. display: inline-block;
  53. max-width: 100%;
  54. overflow: hidden;
  55. text-overflow: ellipsis;
  56. white-space: nowrap;
  57. }
  58. </style>