故事背景: 產(chǎn)品在移動(dòng)端提出文本超過 4 行需要...顯示并且支持點(diǎn)擊按鈕展開, 實(shí)現(xiàn)起來其實(shí)還是比較簡(jiǎn)單的, 但是怎么把代碼寫的最優(yōu)雅呢, 今天把自己的實(shí)現(xiàn)方案貼出來供大家參考
<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>>