<template>
  <el-tooltip
    :disabled="!overflow"
    :content="text"
    :open-delay="500"
  >
    <div
      ref="target"
      class="u-ellipsis u-readonly"
    >
      {{ text }}
    </div>
  </el-tooltip>
</template>

<script>
export default {
  name: 'AutoText',
  props: {
    text: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      overflow: false
    }
  },
  watch: {
    text () {
      this.$nextTick(this.checkSize)
    }
  },
  mounted () {
    this.checkSize()

    window.addEventListener('resize', this.checkSize)
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.checkSize)
  },
  methods: {
    checkSize () {
      const target = this.$refs.target
      if (target) {
        this.overflow = this.text?.length ? target.scrollWidth > target.offsetWidth : false
      }
    }
  }
}
</script>
