Johniya Blog
首页 博客 社区 问答 开发者 约米云盘 注册
组件傻瓜式即插即用文本溢出解决
默凌 2023-11-12 18:21:39 北京 Vue 前端 开发

文本溢出时显示省略号“...”。并且在hover时显示气泡tooltip展示完整内容。
优点:tooltip气泡只在已经溢出的文本上显示,不溢出时不显示气泡。

<template>
  <el-tooltip class="item" effect="dark" :content="$slots.default[0].text" placement="top-start" :disabled="!show">
    <span ref="text" class="hidden-text" :style="{ width: width }">
      {{ $slots.default[0].text }}
    </span>
  </el-tooltip>
</template>

<script>
export default {
  name: 'HiddenSpan',
  props: {
    width: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      show: false
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.calc()
    })
  },
  methods: {
    calc() {
      const text = this.$refs.text
      this.show = (text.scrollWidth > text.clientWidth)
    }
  }
}
</script>

<style scoped>
.hidden-text {
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
  white-space: nowrap;
}
</style>

云服务器 免费试用 一键搭建个人网站 现在购买,领取免费顶级域名 糯米云
5
1
0
21
评论 0
@Johniya.top