主要实现当数据不超过6个时候不展示展开和收起。超过6个且是处于未展开的状态下,则展示前6个数据。
实现思路:
1.当所要循环的数量大于6,则出现展开收起
<div v-if="listData.length > 6"
v-on:click="changeFoldState">
<span>{{brandFold?'展开':'收起'}}</span>
</div>
2.利用计算属性实现。首先判断是否是展开的状态,如果是展开状态则只需要返回就行。如果不是展开状态,判断数据中是否小于6,如果小于6个直接返回所要展示的数据。如果不是则创建一个新数组存放并返回6个数据。
computed: {
showdetailList: {
get: function () {
if (this.brandFold) {
if (this.listData.length < 7) {
return this.listData
}
const newArr = []
for (var i = 0; i < 6; i++) {
const item = this.listData[i]
newArr.push(item)
}
return newArr
}
return this.listData
},
set: function (val) {
this.showdetailList = val
}
}
3.注意:set是根据computed里定义的那个数据来改变其他的数据
set: function (val) {
this.showdetailList = val
}
<template>
<div id='message'>
<div>
<p v-for="(item, index) in showdetailList" :key="index">
<span>{{item.id}}</span>
</p >
</div>
<div v-if="listData.length > 6"
v-on:click="changeFoldState">
<span>{{brandFold?'展开':'收起'}}</span>
</div>
</div>
</template>
<script>
export default {
name: '',
components: {
},
props: {
},
data () {
return {
listData:
[ { id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 },
{ id: 5 },
{ id: 6 },
{ id: 7 },
{ id: 8 },
{ id: 9 }
],
brandFold: true
}
},
created () {
},
mounted () {
},
methods: {
changeFoldState () {
this.brandFold = !this.brandFold
}
},
computed: {
showdetailList: {
get: function () {
if (this.brandFold) {
if (this.listData.length < 7) {
return this.listData
}
const newArr = []
for (var i = 0; i < 6; i++) {
const item = this.listData[i]
newArr.push(item)
}
return newArr
}
return this.listData
},
set: function (val) {
this.showdetailList = val
}
}
},
watch: {
},
filters: {
}
}
</script>
<style lang="less" scoped>
.box {
width: 100px;
height: 100px;
background-color: pink;
}
</style>