城市插件,城市插件安装的是vant组件库提供的
npm i @vant/area-data
安装拼音的插件
npm install pinyin-pro
单独创建一个js文件,获取城市并且处理接收到的数据
import { pinyin } from "pinyin-pro";
import { areaList } from '@vant/area-data';
const city = areaList.city_list;
// const indexList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
let indexList = []
let cityItems = [] // 排好序的内容
function cityList() {
for (let [key,value] of Object.entries(city)) {
let arr = pinyin(value, { pattern: 'initial', type: 'array' })
cityItems.push({
key,
value,
pinyin: arr[0].toUpperCase()
})
}
}
// 根据拼音排序
function formatdata() {
cityItems.sort((c1,c2)=>{
return pinyin(c1.value, { pattern: 'first' }) < pinyin(c2.value,{pattern: 'first'}) ? -1 : 1;
})
// 过滤出地址的首字母
let arrPinyin = cityItems.map((item)=>{
// 插件中开头为a的,都为空,所以要自己处理一下
if(item.pinyin === '') item.pinyin = 'A'
// ch,zh这样的只保留第一个字符
if(item.pinyin.length > 1) item.pinyin = item.pinyin.substring(0,1)
return item.pinyin
})
// 去重
let arr = Array.from(new Set(arrPinyin))
// 若有 a 发音开头的,安排其为排序第一
if(arr.includes('A')) {
indexList[0] = 'A'
arr.splice(arr.length-1,1)
}
indexList = indexList.concat(arr)
}
// 执行函数
cityList();
formatdata()
export {
cityItems,
indexList
}
在vue页面中使用
<template>
<div>
<van-index-bar :index-list="indexList">
<!-- 注释这层div可以看看没有它的效果 -->
<div v-for="i in indexList" :key="i" >
<van-index-anchor :index="i" />
<van-cell v-for="item in cityList" :key="item.key" v-show="item.pinyin === i" :title="item.value" />
</div>
</van-index-bar>
</div>
</template>
<script>
import { cityItems,indexList } from "@/utils/pinyin";
export default {
name: 'CityCell',
data () {
return {
cityList: cityItems,
indexList: indexList
}
},
mounted () {
this.init()
},
methods: {
init() {
console.log("cityList",this.cityList);
console.log("indexList",this.indexList);
}
},
}
</script>
![](https://i-blog.csdnimg.cn/blog_migrate/0f7477f7b73e8a05cb6db2f9f7e15589.png)