1. 타겟 효과
특정 코드는 아래에 있으며 모두 App.vue로 작성되었습니다. 복사하여 붙여넣기만 하면 실행됩니다.
2. 원리 분석
(1) [ {title: 'B', name: 'Beijing'} ]과 유사한 개체 배열을 준비하고 그룹화 기준을 결정합니다.
(2) 객체 배열의 그룹화 작업을 계산 된
(3) 그룹화는 어떻게 하나요? 배열을 순회하고(for 루프, foreach) 루프에서 빈 객체를 생성하고 객체에 한정된 값을 추가하고 마지막으로 객체를 반환합니다. 키 값은 그룹 이름이고 값은 여러 데이터의 배열입니다 .
(4) list.reduce((accumulator, item)=>{ } , {}), reuce 에는 두 개의 매개 변수 가 있습니다 . 우리는 마지막으로 객체에 스플라이싱하기를 원하므로 초기 값은 {} 빈 객체이고 콜백 함수의 첫 번째 매개 변수는 accumulator 이며 이는 reduce의 두 번째 매개 변수와 동일한 유형이며 콜백 함수의 두 번째 값은 일반적으로 감소는 누산기와 현재 값을 통해 일부 작업을 수행하고 배열을 객체로 변환할 수 있는 새로운 누적 결과를 반환하는 것입니다!
3. 특정 코드
<template>
<div id="app">
<el-input placeholder="请输入搜索条件" style="width:300px;" v-model="searchInput"></el-input>
<dl v-for="(item, key, index) in searchList" :key="index">
<dt>{
{ key }}</dt>
<dd v-for="(i,j) in item" :key="j">{
{ i.name }}</dd>
</dl>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
searchInput: '', // 搜索条件
lists:[ // 对象数组
{title: 'B', name: '北京'},
{title: 'B', name: '保定'},
{title: 'B', name: '北海'},
{title: 'C', name: '长春'},
{title: 'C', name: '常德'},
{title: 'A', name: '安庆'},
{title: 'D', name: '大庆'},
{title: 'D', name: '东莞'},
{title: 'F', name: '福州'},
{title: 'F', name: '抚州'},
]
}
},
computed:{
// 将对象数组进行分组(方法一:foreach)
list(){
let groups = {}
this.lists.forEach(item=>{
// item为对象数组中的每个对象,此处根据title进行分组
// value为组名
let value = item['title'];
// 新对象groups判断有无相对应组名,有则保留,否则为空数组
groups[value] = groups[value] || [];
// 向这个组插入数据
groups[value].push(item)
})
// 返回这个经过分组过后的对象
return groups
},
// 将对象数组进行分组(方法二:reduce)
list2(){
// rv为累加器,current为对象数组中的每一项即是一个对象
return this.lists.reduce((rv,current)=>{
(rv[current['title']]=rv[current['title']]||[]).push(current)
return rv
},{})
},
// 搜索分组
searchList(){
let obj = {}
// citys为上面对象数组经过分组过后的数据
let citys = this.list;
if(this.searchInput == ''){
// 搜索为空,则返回初始分组后的数据
return this.list
}else{
// 搜索不为空,通过for in 对 对象进行遍历
for (let key in citys) {
// key为组名,citys[key] 为组名下的多个数据,即城市列表,城市列表下的城市名与搜索条件进行比较,然后筛选出能够找到的城市
let searchResult = citys[key].filter( item=>{
return item.name.indexOf(this.searchInput) != -1
})
// 搜索到目标结果,则返回相对应拼接后的对象
if(searchResult.length > 0){
obj[key] = searchResult
return obj
}
}
}
}
}
}
</script>
<style>
#app {
text-align: center;
margin: 0;
padding: 0;
box-sizing: border-box;
font-size: 16px;
}
</style>