1, demo show
2, unprocessed data
3, the data to be processed in the form of
4, a method,
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() 并没有改变数组的原始值。