1

table-tooltip组件

  1. 组件中 外层元素和内层元素的样式写在style里,正常添加tooltip后,不管内层元素长度是否大于外元素宽度,都会显示tooltip
  2. 所以要根据外层元素的宽度加一层判断放在tooltip的disabled里,虽然我们能够在组件初始化时在mounted中获取到父子元素的宽度,但当表格字段宽度变化时,无法实时响应disabled值,你可能会想到用watch来监听元素的宽度,但实际vue中并不能够监听dom的长宽
  3. 所以我们这里使用自定义指令在添加局部指令,来监听元素宽度的变化,代码如下:
<template>
  <div class="t-tooltip" ref="outer" v-resize="resize">
    <el-tooltip
      :content="String(content)"
      :disabled="disabled"
      effect="dark"
      placement="top-start">
      <span ref="inner" class="t-tooltip-content">{{ String(content) }}</span>
    </el-tooltip>
  </div>
</template>

<script>

export default {
  name: 'TableTooltip',
  components: {},
  props: {
    content: {
      type: [Number, String]
    }
  },
  data() {
    return {
      disabled: false
    }
  },
  computed: {
  },
  watch: {
  },
  directives: {
    // 采用局部注册的方法, 监控父元素宽度变化
    resize: {
      bind(el, binding) {
        let width = '';
        function isReize() {
          const style = document.defaultView.getComputedStyle(el);
          if (width !== style.width) {
            binding.value();  // 关键
          }
          width = style.width;
        }
        el.__vueSetInterval__ = setInterval(isReize, 1200);
      },
      unbind(el) {
        clearInterval(el.__vueSetInterval__);
      }
    }
  },
  created() {},
  mounted() {
    this.disabled = this.$refs.inner.offsetWidth < this.$refs.outer.offsetWidth
  },
  methods: {
    resize() {
      this.disabled = this.$refs.inner.offsetWidth < this.$refs.outer.offsetWidth
    }
  }
}
</script>

<style lang="less" scoped>
  .t-tooltip {
    height: 100%;
    margin-bottom: 4px;
    word-break: break-all;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 18px;
    &-content {
      white-space: nowrap;
      word-break: break-all;
    }
  }
</style>

chidaozhi
60 声望4 粉丝

前端老阿姨