问题描述:
vue实现搜索记录只显示两行,超出两行内容隐藏且显示展开按钮。(实现效果参考美团app历史搜索)
解决思路:
定义两个父盒子,一个用来渲染全部数据但是最后隐藏盒子
第一个盒子渲染完成后根据拿取第一个盒子中渲染的每一个子元素的宽度计算应该截取到第几个子元素,然后把数据截取赋值给第二个盒子去渲染,此时隐藏第一个盒子
第二个盒子渲染出来的就是两行数据
效果图:
代码:
<template>
<div>
<div class="box" id="dis">
<div v-for="item in data" class="item">{{ item }}</div>
</div>
<div class="box ">
<div v-for="item in currentdata" class="item">{{ item }}</div>
<div class="btn" @click="partcahnge" v-if="btnShow">
<span v-if="part">展开</span>
<span v-else>收起</span>
</div>
</div>
</div>
</template>
export default {
name: '',
props: {
data: {
type: Array,
default: () => ['afwerwewef', 'abfwefc', 'asdfghjeddefrtyuuiiohgfxgchvjbkhgfgdsdgfhgj', 'asdfghjeddefrtyuuiiohgfxgchvjbkhgfgdsdgfhgj']
}
},
data() {
return {
partdata: [],
currentdata: [],
part: true,
btnShow: true,
}
},
methods: {
partcahnge() {
if (this.part) {
this.part = false
this.currentdata = this.data
} else {
this.part = true
this.currentdata = this.partdata
}
}
},
created() {
},
mounted() {
const dis = document.getElementById('dis')
let wid1 = 0
let wid2 = 0
try {
dis.childNodes.forEach((item, idx) => {
wid1 += item.clientWidth + 20
if (wid1 > 400) {
wid2 += item.clientWidth + 20
}
if (wid2 <= 340) {
this.partdata.push(this.data[idx])
this.currentdata = this.partdata
} else {
throw new Error()
}
})
} catch {
} finally {
if (wid2 <= 340) {
this.btnShow = false
}
dis.className = 'disn'
}
},
}
<style lang="scss" scoped>
.box {
background-color: antiquewhite;
display: flex;
width: 400px;
flex-wrap: wrap;
.item {
background-color: aliceblue;
height: 20px;
margin: 5px 10px;
padding: 5px;
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis; //溢出用省略号显示
white-space: nowrap; //溢出不换行
}
.btn {
height: 20px;
width: 40px;
text-align: center;
margin: 10px;
border-radius: 50%;
background-color: #fff;
line-height: 20px;
cursor: pointer;
span {
font-size: 12px;
}
}
}
.disn {
display: none;
}
</style>