1.基本需求
返回多条数据,每条数据在一定宽度的盒子内,文本超过三行进行文本的展开与收起
2.实现逻辑
对于返回的每条数据添加属性expend:false来在循环中进行对于展开收起的判断。
动态计算盒子宽度随着分辨率的变化而变化的值boxWidth。获取返回数据文本长度*字体大小除3与boxWidth值进行比较(动态判断展开与收起是否展示)
3.代码
<template>
<div class="all">
<div class="content" ref="box">
<!-- 循环数据 -->
<div class="contentAll" v-for="(item,index) in List" :key="index" >
<div class="details" >
<!-- 内容 -->
<!-- 动态切换类名 进行展开与收起 -->
<div :class="{'text-container': !item.expand, 'expand':item.expand }">{{ item.remark }}</div>
<!-- 通过item.remark.length*14/3 获取文本字数*字体大小/3判断是否超过盒子宽度 -->
<div v-if="item.remark.length*14/3>=boxWidth" class="btn" @click="toggleExpand(index)">{{ item.expand ? '收起' : '展开' }}</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'ye',
data(){
return{
// 宽度
boxWidth: 0,
List: [
{
expand:false,
remark: "呀呀呀呀呀呀哎呀呀",
},
],
}
},
// 进行监听屏幕的分辨率 进行计算宽度
mounted() {
window.addEventListener('resize', this.handleResize)
},
// 移除监听
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
// 动态获取盒子宽度
handleResize() {
// 通过this.$refs.box.offsetWidth获取盒子宽度
const width = this.$refs.box.offsetWidth;
if (width!=0) {
this.boxWidth=width-40;
}
},
// 动态点击取反(展开与收起)
toggleExpand(index) {
this.List[index].expand = !this.List[index].expand
},
// 请求后端数据返回
queryList() {
// 对于接口请求的数据结构 每一个元素添加展开收起的初始值.expand = false;
Api.a.then(resp => {
let arr = resp.data;
for (let iterator of arr) {
iterator.expand = false;
}
this.List = arr;
})
},
},
// 初始加载时,进行计算
activated() {
this.handleResize()
},
}
</script>
<style lang="less" scoped>
// 内容块
.contentAll {
flex-grow: 0;
flex-shrink: 0;
list-style: none;
box-sizing: border-box;
padding-left: 40px;
position: relative;
}
.content{
height:500px;
width:100%;
overflow-y:scroll;
overflow-x: hidden;
}
.details {
display: flex;
align-items: baseline;
min-height: 80px;
margin-left: 10px;
border-bottom: 1px solid #d5d5d5 ;
}
/* 默认显示3行,超出部分隐藏 */
.text-container {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 3; /* 行数 */
-webkit-box-orient: vertical;
}
/* 点击按钮后展开 */
.expand {
-webkit-line-clamp: initial; /* 移除行数限制 */
}
.btn{
width: 140px;
height: 40px;
cursor: pointer;
color: #006eff;
}
</style>
4.总结
缺点就是没有精确的计算返回文本的长度,汉字,数字,字母,空格以及字间距没有完全精确的计算会导致(展开与收起)判断出现不准确