<template>
<div class="wrap">
<van-index-bar>
<div v-for="item in filterData" :key="item.letter">
<van-index-anchor :index="item.letter"></van-index-anchor>
<div
class="content"
v-for="row in item.list"
:key="row.id"
@click="go(row.id)"
>
{{ row.name }}
</div>
</div>
</van-index-bar>
</div>
</template>
<script>
export default {
name: "test",
data() {
return {
filterData: [], // 处理后的 待渲染数据
// 模拟数据
mapData: [
{
id: 1,
name: "万景千言",
},
{
id: 2,
name: "八里沟11",
},
{
id: 2,
name: "八里沟1",
},
{
id: 2,
name: "八里沟",
},
{
id: 17,
name: "京华园",
},
{
id: 21,
name: "平原博物馆",
},
{
id: 38,
name: "金牛湖野生动物王国",
},
],
};
},
created() {
this.test();
},
methods: {
test() {
// 安装使用 js-pinyin 插件,获取待处理字段的拼音
const pinyin = require("js-pinyin");
this.mapData.map((item) => {
item.pinyin = pinyin.getFullChars(item.name);
});
let provice = {};
this.mapData.map((item) => {
const Initials = item.pinyin[0].toUpperCase();
// 如果对象里有当前字母项则直接 push 一个对象,如果没有则创建一个新的键并赋值;
if (provice[Initials]) {
provice[Initials].push(item);
} else {
provice[Initials] = [item];
}
});
// 将数据转为数组,并按字母顺利排列
this.filterData = [];
for (let key in provice) {
const obj = { letter: key, list: provice[key] };
this.filterData.push(obj);
}
this.filterData.sort((a, b) => {
return a.letter.localeCompare(b.letter);
});
},
},
};
</script>