赞助

vant: https://youzan.github.io/vant/#/zh-CN/

 

 安装

cnpm i -S vant

按需加载配置

#  babel.config.js 中配置

 

module.exports = {
  plugins: [
    ['import', {
      libraryName: 'vant',
      libraryDirectory: 'es',
      style: true
    }, 'vant']
  ],
  presets: [
    '@vue/cli-plugin-babel/preset'
  ]
}

 

对于获取到的城市数据进行处理创建个api.js文件


 // 引入封装头信息和请求域名的axios对象
import http from './http'
 // 引入请求的url地址
import{
  cityUri
} from '../config/uri'
export const cityData = async () => {
  // 判断本地是否有缓存,如果有则不请求远程数据
  let cacheData = !localStorage.getItem('cityData') ? [] : JSON.parse(localStorage.getItem('cityData'))
  if(cacheData.length > 0){
    return Promise.resolve(cacheData)
  }
  let ret = await http.get(cityUrl,{
    headers:{
      // 由于请求头信息中不同的需求不同的请求头,所以要判断所用的条件
      'info':'city'
    }
  })
  let retData = ret.data.cities
  // 城市字母索引
  let cityIndex = []
  // 处理完成后的数据
  let dataList = []
  let indexList = []
  for(let i = 65 ; i <= 90 ; i++){
    // 这是String.fromCharCode的示例 可接受一个指定的 Unicode 值,然后返回一个字符串
    // document.write(String.fromCharCode(65,66,67) )   输出 ABC 
    cityIndex.push(String.fromCharCode(i))
  }
  cityIndex.forEach(index => {
    let tmpArr = retData.filter(item => index.toLowerCase() == item.pinyin.substr(0,1))
    if(tmpArr.length > 0){
      indexList.push(index)
      dataList.push({
        index,
        data:tmpArr
      })
    }
  })
  let data = [dataList,indexList]
  localStorage.setItem('cityData',JSON.stringify(data))
  return Promise.resolve([dataList,indexList])
  }

在组件中使用

<template>
  <div>
    <van-index-bar :index-list="indexList" highlight-color="#ff0000">
      <template v-for="item in datalist">
        <van-index-anchor :index="item.index" :key="item.index" />
        <van-cell v-for="subitem in item.data" :title="subitem.name" />
      </template>
    </van-index-bar>
  </div>
</template>

<script>
import Vue from 'vue'
import { IndexBar, IndexAnchor, Cell } from 'vant'
import { cityData } from '../../api/api'
Vue.use(IndexBar)
Vue.use(IndexAnchor)
Vue.use(Cell)
export default {
  data() {
    return {
      dataList: [],
      indexList: ['A', 'B']
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    async getData() {
      const ret = await cityData()
      this.datalist = ret[0]
      this.indexList = ret[1]
    }
  }
}
</script>

<style></style>

 

posted on 2021-01-13 11:18  Tsunami黄嵩粟  阅读(841)  评论(0编辑  收藏  举报