vue3封装全局使用超出tips

javascript 复制代码
<template>
  <div class="text-ellipsis-wrapper">
    <el-tooltip
      v-if="isOverflow"
      :content="text"
      :placement="placement"
      :effect="effect"
      :disabled="!isOverflow"
      :enterable="enterable"
    >
      <span
        ref="textRef"
        class="text-ellipsis"
        :style="{
          maxWidth: maxWidth,
          fontSize: fontSize,
          color: color,
          fontWeight: fontWeight,
        }"
      >
        {{ text }}
      </span>
    </el-tooltip>
    <span
      v-else
      ref="textRef"
      class="text-ellipsis"
      :style="{
        maxWidth: maxWidth,
        fontSize: fontSize,
        color: color,
        fontWeight: fontWeight,
      }"
    >
      {{ text }}
    </span>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'

// Props
const props = defineProps({
  text: {
    type: [String, Number],
    default: '',
  },
  maxWidth: {
    type: String,
    default: '100px',
  },
  fontSize: {
    type: String,
    default: '12px',
  },
  color: {
    type: String,
    default: '#333',
  },
  fontWeight: {
    type: String,
    default: 'normal',
  },
  placement: {
    type: String,
    default: 'top',
  },
  effect: {
    type: String,
    default: 'dark',
  },
  enterable: {
    type: Boolean,
    default: true,
  },
})

// Refs
const textRef = ref(null)
const isOverflow = ref(false)

// Methods
const checkOverflow = () => {
  nextTick(() => {
    const el = textRef.value
    if (el) {
      isOverflow.value = el.scrollWidth > el.clientWidth
    }
  })
}

const handleResize = () => {
  checkOverflow()
}

// Lifecycle
onMounted(() => {
  checkOverflow()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})

// Watchers
watch(
  () => props.text,
  () => {
    checkOverflow()
  }
)

watch(
  () => props.maxWidth,
  () => {
    checkOverflow()
  }
)
</script>

<style scoped>
.text-ellipsis-wrapper {
  display: inline-block;
  width: 100%;
  white-space: nowrap;
}

.text-ellipsis {
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  display: inline-block !important;
  width: 100% !important;
  vertical-align: middle !important;
  max-width: 100%;
  word-break: keep-all !important;
  word-wrap: normal !important;
  overflow-wrap: normal !important;
}
</style>

运用:

javascript 复制代码
import TextEllipsis from "../components/TextEllipsis.vue";
// 全局注册
Vue.component("TextEllipsis", TextEllipsis);
javascript 复制代码
<TextEllipsis   :text="'文字'"   :maxWidth="'110px'" />