1、demo展示

2、未處理的數據

3、要處理數據的形式

4、方法一、
created() { console.log(this.dataList) this.dataList.forEach((data) => { for(let i = 0; i<this.textList.length; i++) { if (this.textList[i].name === data.name) { this.textList[i].contentList.push(data.content) return } } this.textList.push({ name: data.name, title: data.title, content:data.content, contentList: [data.content] }) }) console.log(this.textList) },
5、方法二、
let map = {}, Arr = [] for (let v of dataList) { if (!map[v.name]) { Arr.push({ name: v.name, title: v.title, content: v.content, arr:[] }) map[v.name] = v } else { for(let x of Arr){ if(x.name == v.name){ x.arr.push(v); break } } } } console.log('最終輸出:',Arr)
6、原生折疊面的展開和收縮


demo源碼
<template>
<div class="box">
<div v-for="(item,index) in textList" :key="index">
<div class="wrapBox" @click="handleclick(index)">
<span>{{item.title}}</span>
</div>
<!-- includes() 方法用來判斷一個數組是否包含一個指定的值,如果是返回 true,否則false -->
<div class="content" v-show='showIndex.includes(index)' v-for="item2 in item.contentList">
<p>{{item2}}</p>
</div>
</div>
</div>
</template>
<script>
export default {
data () {
return {
// 定義一個數組存放index的值
showIndex:[],
dataList: [
{
name: 1,
title: '史蒂夫·喬布斯1',
content: '史蒂夫·喬布斯1-1',
},
{
name: 1,
title: '史蒂夫·喬布斯1',
content: '史蒂夫·喬布斯1-2',
},
{
name: 1,
title: '史蒂夫·喬布斯1',
content: '史蒂夫·喬布斯1-3',
},
{
name: 2,
title: '史蒂夫·喬布斯2',
content: '史蒂夫·喬布斯2-1',
},
{
name: 3,
title: '史蒂夫·喬布斯3',
content: '史蒂夫·喬布斯3-1',
},
{
name: 3,
title: '史蒂夫·喬布斯3',
content: '史蒂夫·喬布斯3-2',
},
{
name: 3,
title: '史蒂夫·喬布斯3',
content: '史蒂夫·喬布斯3-3',
},
{
name: 3,
title: '史蒂夫·喬布斯3',
content: '史蒂夫·喬布斯3-4',
},
{
name: 3,
title: '史蒂夫·喬布斯3',
content: '史蒂夫·喬布斯3-5',
},
{
name: 2,
title: '史蒂夫·喬布斯2',
content: '史蒂夫·喬布斯2-2',
},
{
name: 2,
title: '史蒂夫·喬布斯2',
content: '史蒂夫·喬布斯2-3',
},
],
textList: [],
contentList: []
}
},
created() {
console.log(this.dataList)
this.dataList.forEach((data) => {
for(let i = 0; i<this.textList.length; i++) {
if (this.textList[i].name === data.name) {
this.textList[i].contentList.push(data.content)
return
}
}
this.textList.push({
name: data.name,
title: data.title,
content:data.content,
contentList: [data.content]
})
})
console.log(this.textList)
},
methods: {
// 點擊折疊版收縮展開
handleclick(index){
console.log(index)
if(this.showIndex.includes(index)){
this.showIndex.splice(
this.showIndex.findIndex(res=>{return res == index}),1
)
}else {
this.showIndex.push(index)
}
}
}
}
</script>
<style>
.box {
width: 900px;
margin: 0 auto;
}
.wrapBox {
text-align: left;
text-indent: 2em;
line-height: 50px;
width: 500px;
height: 50px;
border: solid 1px #2C3E50;
background: lightgray;
}
.content {
text-align: left;
padding-left: 200px;
}
</style>
數組findIndex補充,來自菜鳥教程https://www.runoob.com/jsref/jsref-findindex.html
findIndex() 方法返回傳入一個測試條件(函數)符合條件的數組第一個元素位置。
findIndex() 方法為數組中的每個元素都調用一次函數執行:
- 當數組中的元素在測試條件時返回 true 時, findIndex() 返回符合條件的元素的索引位置,之后的值不會再調用執行函數。
- 如果沒有符合條件的元素返回 -1
注意: findIndex() 對於空數組,函數是不會執行的。
注意: findIndex() 並沒有改變數組的原始值。
