vue中使用el-tooltip实现超出部分显示省略号且移入显示el-tooltip内容

vue中使用el-tooltip实现超出部分显示省略号且移入显示el-tooltip内容

  • vue中使用el-tooltip实现超出部分显示省略号且移入显示el-tooltip内容

vue中使用el-tooltip实现超出部分显示省略号且移入显示el-tooltip内容

自定义组件MyTooltip.vue

<template>
  <div class="tooltip-container">
    <el-tooltip class="my-tooltip" :disabled="showTooltip" :content="text">
      <p ref="tooltipBox" class="text-box">
        <span ref="tooltipItem">{{ text }}</span>
      </p>
    </el-tooltip>
  </div>
</template>

<script>
export default {
  name: "myTooltip",
  props: {
    text: {
      type: String,
      default: () => ""
    }
  },
  data() {
    return {
      showTooltip: true
    }
  },
  watch: {
    text: {
      handler() {
        this.$nextTick(() => this.checkWidth());
      },
      immediate: true
    }
  },
  methods: {
    checkWidth() {
      const boxWidth = this.$refs['tooltipBox'].offsetWidth;
      const itemWidth = this.$refs['tooltipItem'].offsetWidth;
      console.log(boxWidth, itemWidth);
      this.showTooltip = boxWidth > itemWidth
    }
  }
};
</script>
<style scoped lang="scss">
.tooltip-container {
  width: 100%;
  .text-box {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
</style>

在页面中使用自定义组件MyTooltip.vue

<template>
  <div>
    <div class="test">
      <MyTooltip :text="'没超出aaa'"></MyTooltip>
    </div>
    <div class="test">
      <MyTooltip :text="'超出aaaaaaaaaaaaaaaa'"></MyTooltip>
    </div>
  </div>
</template>
<script>
import MyTooltip from "@/components/MyTooltip";
export default {
  components: {MyTooltip}
}
</script>
<style lang="scss">
.test {
  width: 150px;
  height: 20px;
  cursor: pointer;
  border: 1px solid #ccc;
}
</style>

结果
在这里插入图片描述

你可能感兴趣的:(vue.js,javascript,前端)