按拼音排序展示城市

  1. 城市插件,城市插件安装的是vant组件库提供的

npm i @vant/area-data
  1. 安装拼音的插件

npm install pinyin-pro
  1. 单独创建一个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
}
  1. 在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> 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值