Vue2.x + element-ui 通过计算文字宽度,判断是否显示更多按钮,然后在弹框中展示全部文字
import { Dialog, Button } from 'element-ui'
import { useSpUI } from './partner-tools'
import './moreColumn.scss'
export default {
components: {
...useSpUI({ Dialog, Button }),
},
props: {
moreData: { type: String, require: true },
title: { type: String, default: '客户需求' },
},
data() {
return {
visible: false, // 是否展示弹框
}
},
methods: {
/**
@description 计算目标文字宽度
*/
getTextWidth(text, font = 'normal 12px PingFangSC-Regular') {
this.canvas = null
const canvas = this.canvas || (this.canvas = document.createElement('canvas'))
const context = canvas.getContext('2d')
context.font = font
return context.measureText(text).width
},
/**
* @description 数据展示及更多按钮判断
*/
moreColumn() {
if (!this.moreData) return '-'
const width = this.getTextWidth(this.moreData)
console.log(width)
// 如果文字累计的宽度,大于目标值宽度则显示更多
if (width > 560) {
return (
<div class='more-warpper'>
<p class='more-item'>{this.moreData}</p>
<sp-button type='text' onclick={() => (this.visible = true)} class='btn-more'>
更多
<i class='sp-icon-right' />
</sp-button>
</div>
)
} else {
return <p class='more-item'>{this.moreData}</p>
}
},
/**
* @description 更多弹框展示
*/
moreDialog() {
return (
<sp-dialog
title={this.title}
visible={this.visible}
{...{ on: { 'update:visible': val => (this.visible = val) } }}
close-on-click-modal={true}
width='500px'>
<div class='more-column_content'>{this.moreData}</div>
<div slot='footer' class='dialog-footer'>
<sp-button onclick={() => (this.visible = false)}>关闭</sp-button>
</div>
</sp-dialog>
)
},
},
render() {
return (
<div class='more-column'>
{this.moreColumn()}
{this.moreDialog()}
</div>
)
},
}
.more-column {
.more-warpper {
display: flex;
.more-item {
flex: 1;
width: 100%;
line-height: 20px;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
line-clamp: 2;
}
.btn-more {
width: 30px;
padding: 0;
}
}
.sp-dialog__body {
padding-top: 0;
}
}