一、demo展現html
二、未處理的數據數組
三、要處理數據的形式函數
四、方法1、測試
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) },
五、方法2、this
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)
六、原生摺疊面的展開和收縮spa
demo源碼3d
<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.htmlcode
findIndex() 方法返回傳入一個測試條件(函數)符合條件的數組第一個元素位置。htm
findIndex() 方法爲數組中的每一個元素都調用一次函數執行:blog
注意: findIndex() 對於空數組,函數是不會執行的。
注意: findIndex() 並無改變數組的原始值。