故事背景: 产品在移动端提出文本超过 4 行需要...显示并且支持点击按钮展开, 实现起来其实还是比较简单的, 但是怎么把代码写的最优雅呢, 今天把自己的实现方案贴出来供大家参考
<template>
<div>
<p class="line-clamp">{{ content }}</p>
<i v-if="showBtn" @click="handleUpdateStyle"> {{ unflod ? '展开更多>>>' : '收起' }}</i>
</div>
</template>
<script>
export default {
props: ['content'],
data() {
return {
showBtn: false,
unflod: true
}
},
async mounted() {
await this.$nextTick()
const { scrollHeight, offsetHeight } = this.$el.querySelector('p')
if (scrollHeight > offsetHeight) {
this.showBtn = true
}
},
methods: {
handleUpdateStyle() {
const hasAttr = this.$el.querySelector('p')?.getAttribute?.('class')?.includes('line-clamp')
this.$el.querySelector('p')?.classList[hasAttr ? 'remove' : 'add']('line-clamp')
this.unflod = !hasAttr
}
}
}
</script>
<style lang="scss" scoped>
.line-clamp {
display: -webkit-box;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
overflow: hidden;
word-break: break-all;
}
i {
color: #3e98ff;
}
</style>>