首先要进行导入注册
import { createApp } from 'vue';
import { IndexBar, IndexAnchor } from 'vant';
const app = createApp();
app.use(IndexBar);
app.use(IndexAnchor);
发送请求,后端接收到数据
onMounted(()=>{
list()
})
const list = async()=>{
var {data} = await axios.get("http://localhost:3000/list")
console.log(data);
}
接收到的数据如下所示
大写字母已经使用pinyin-pro在后端转换好啦!如下:
router.get("/list",async (req,res)=>{
var data = JSON.parse(fs.readFileSync("json/city.json"))
var obj = {}
data.RECORDS.forEach(ele=>{
obj[ele.code] = ele
})
var list = []
data.RECORDS.forEach(ele=>{
if(ele.type==1){
list.push(ele)
}else{
if(!obj[ele["superior"]]["children"]){
obj[ele["superior"]]["children"] = []
}
obj[ele["superior"]]["children"].push(ele)
}
})
//给列表添加转换好的大写字母
let ls = list.map((item,index)=>{
var pin = pinyin(item.name,{toneType:'none'}).toUpperCase()[0]
return {...item,pinyin:pin}
})
res.send(ls)
})
可以通过分组函数对接收到的数据进行分组
// 分组函数
const filterCity = (list) => {
let letterArray = [];
//生成A-Z的英文字母
for (let i = 65; i < 91; i++) {
//将当前字符编码 i 转换为对应的字母
letterArray.push(String.fromCharCode(i));
}
let newCities = []
letterArray.forEach(item => {
newCities.push({
type: `${item}`,
list: list.filter(item1 => item1.pinyin === `${item}`)
})
})
newCities = newCities.filter(item => item.list.length)
console.log(newCities);
return newCities;
}
在接收数据处调用,根据每个字母进行分组,ls数组中就是得到的数据
var ls = ref([])
const list = async()=>{
var {data} = await axios.get("http://localhost:3000/list")
ls.value = filterCity(data)
}
得到的结果如下所示
在模板中使用
<van-index-bar :index-list="indexList">
<div v-for="item in ls" :key="item.type">
<van-index-anchor :index="item.type"/>
<van-cell v-for="(ele,index) in item.list" :key="index" :title="ele.name" />
</div>
...
</van-index-bar>
模板中的:index-list绑定的是对应的字母,可以通过计算属性获取到数组中所有的字母
//获取所有字母
const indexList = computed(() => {
return ls.value.map(item => item.type)
})
最后展示前端全部代码
<template>
<van-index-bar :index-list="indexList">
<div v-for="item in ls" :key="item.type">
<van-index-anchor :index="item.type"/>
<van-cell v-for="(ele,index) in item.list" :key="index" :title="ele.name" />
</div>
...
</van-index-bar>
</template>
<script setup>
import axios from "axios"
import {onMounted,ref,computed} from "vue"
onMounted(()=>{
list()
})
var ls = ref([])
const list = async()=>{
var {data} = await axios.get("http://localhost:3000/list")
ls.value = filterCity(data)
console.log(ls.value);
}
//获取所有字母
const indexList = computed(() => {
return ls.value.map(item => item.type)
})
// 分组函数
const filterCity = (list) => {
let letterArray = [];
for (let i = 65; i < 91; i++) {
letterArray.push(String.fromCharCode(i));
}
let newCities = []
letterArray.forEach(item => {
newCities.push({
type: `${item}`,
list: list.filter(item1 => item1.pinyin === `${item}`)
})
})
newCities = newCities.filter(item => item.list.length)
console.log(newCities);
return newCities;
}
</script>
<style>
</style>
以下是渲染出来的结果
ok啦!!!这篇手工!!!