1.写一个样式
<!-- 评论 -->
<div class="message-item">
<div style="margin-bottom: 10px;">
//如果isShowExpanded为true则评论展开,否则收起
<p class="comment_content" :class="item.isShowExpanded ? '' : 'active'">
{{ item.content }}
</p>
</div>
<div class="comment_btn" v-if="item.isShow" @click="handleShow(item)">
//isShowExpanded为true则表示评论为展开状态,按钮应该显示为“收起”字样
{{ item.isShowExpanded ? '收起' : '展开' }}
</div>
</div>
2.添加标识
从后端获得需要的数组,给数组的每个对象添加两个标识: isShowExpanded-是否显示“展开” “收起”按钮 isShow-是否展开评论 如果你的后端好说话,就让Ta给你直接加个字段就行了,如果不好说话,那你就只能自己加咯
```// 给所有评论添加标识
const getAll = () => {//allTypeMessageList是目标数组
allTypeMessageList.value.forEach(item => {
item.isShow = false;//全部赋值为false,不显示按钮
item.isShowExpanded = true;//全部赋值为true,评论展开
if (item.content.length > 66) {//当评论的长度大于66时
item.isShow = true;//显示“展开”按钮
item.isShowExpanded = false;//评论折叠为两行
}
})
}
```js
grtAll()函数调取时,一定要在获取allTypeMessageList数组的函数里调取,否则会出现数组为空的错误,导致控制失效
3.点击按钮控制评论是否展开
通过改变isShowExpanded的布尔值,来控制
const handleShow = (item) => {
item.isShowExpanded = !item.isShowExpanded
}
4.样式
采用定位的方式,把展开按钮固定在一个位置
.message-item {
position: relative;
}
//采用rem可以让按钮不论屏幕怎么缩放都在同一个位置
.comment_btn {
position: absolute;
right: 1.5rem;
top: 3.5rem;
background-origin: 0;
color: #5191FF;
font-weight: bold;
cursor: pointer;
user-select: none;
}
.comment_content {
margin-top: 10px;
color: #77749d;
line-height: 22px;
text-align:justify;
// position:relative;
}
.comment_content.active {
overflow: hidden;
text-overflow:ellipsis;
display:-webkit-box;
-webkit-line-clamp:2;
-webkit-box-orient:vertical;
}