element表格文本超出指定行使用popover展示

2024-10-17  本文已影响0人  坐在天台吹吹风

场景描述

使用element-ui开发后台管理,列表使用表格展示,有的字段内容会比较长。

展示及弊端

  1. 直接在列表进行展示,某个字段总是内容很长,会造成表格过高,同时也不美观。
  2. 使用show-overflow-tooltip属性,过长内容表格展示会隐藏,但是气泡框展示的时候内容过宽同样不美观。
  3. 对字段长度进行判断,大于设置长度展示气泡框,小于不展示。这样又会因为不同字符宽度不等,导致判断不精准,同样长度时表现不一致。

期待展示

需要表现一致的解决办法,内容少可以完全展示的时候不显示弹框直接展示,超出固定行数时展示弹框。

代码实现

以下代码作为示例,对其中remark字段进行判断,超出两行表格内显示省略号,弹框展示全部内容。

<el-table v-loading="loading" :data="list">
  <el-table-column label="姓名" align="center" prop="name"/>
  <el-table-column label="地址" align="center" prop="address" show-overflow-tooltip/>
  <el-table-column :key="componentKey" label="备注" align="center" prop="remark">
    <template slot-scope="{row}">
      <el-popover placement="left" width="500" trigger="hover" v-if="!popBool[row.id]" :content="row.remark">
        <div :ref="'popper'+row.id" slot="reference" class="remark-wrap">{{ row.remark }}</div>
      </el-popover>
      <div v-else>
        {{ row.remark }}
      </div>
    </template>
  </el-table-column>
  <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
</el-table>
componentKey: 0,
popBool: [], //false显示pop,true不显示

// 列表查询方法
getList() {
  queryTable().then(res => {
    this.list = res.rows;
    setTimeout(() => {
      for (var i = 0; i < this.list.length; i++) {
        let lineHeight = getComputedStyle(this.$refs['popper' + this.list[i].id]).lineHeight.replace('px', '') - 0; //单行文字的行高
        let scrollHeight = this.$refs['popper' + this.list[i].id].scrollHeight; //文字实际高度
        scrollHeight > lineHeight * 2 ? this.popBool[this.list[i].id] = false : this.popBool[this.list[i].id] = true; //高度大于2行,有省略
        this.componentKey++; //改变key,对组件重新渲染。
      }
    }, 500);
  });
},
<style scoped>
.remark-wrap {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}
</style>

注意点

思考

如果一个table中有不止一个字段需要这样展示,又应该怎么设置?
假如以上代码中name字段同样需要超出展示,我们可以进行如下修改。

<el-table-column :key="'name'+componentKey" label="姓名" align="center" prop="name">
  <template slot-scope="{row}">
    <el-popover placement="left" width="500" trigger="hover" v-if="!popBoolName[row.id]" :content="row.name">
      <div :ref="'popperName'+row.id" slot="reference" class="remark-wrap">{{row.name}}</div>
    </el-popover>
    <div v-else>
      {{ row.name }}
    </div>
  </template>
</el-table-column>
popBoolName: [],

let scrollHeight1 = this.$refs['popperName' + this.list[i].id].scrollHeight; //文字实际高度
scrollHeight1 > lineHeight * 2 ? this.popBoolName[this.list[i].id] = false : this.popBoolName[this.list[i].id] = true; //高度大于2行,有省略

修改说明

参考链接

vue实现判断文本是否超出,超出后显示省略号并且hover展示全部内容,未超出的不加 Popover 弹出框

上一篇 下一篇

猜你喜欢

热点阅读