<template>
  <div>
    <div @mouseenter="e => isShowToltip(e)" @mouseout="hideTip()" v-if="!isShow" class="text">
      {{ text }}
      <slot></slot>
    </div>
    <el-tooltip v-if="isShow" class="item" effect="dark" :content="text" placement="top">
      <div class="text">{{ text }}</div>
    </el-tooltip>
  </div>
</template>

<script>
export default {
  props: {
    text: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isShow: false
    }
  },
  methods: {
    isShowToltip(e) {
      const bool = this.textRange(e.target) //如果文本超出宽度才显示tooltip
      this.isShow = bool
    },
    hideTip() {
      this.isShow = false
    },
    // el dom元素
    textRange(el) {
      //计算文本超出宽度了没
      const textContent = el
      const targetW = textContent.getBoundingClientRect().width //获取文本宽度
      const range = document.createRange()
      range.setStart(textContent, 0) //生成一个文本节点
      range.setEnd(textContent, textContent.childNodes.length)
      const rangeWidth = range.getBoundingClientRect().width
      return rangeWidth > targetW
    }
  }
}
</script>

<style scoped>
.text {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
