城市选择数据渲染

it2026-03-16  1

要求:

点击右边索引栏时,会自动跳转到对应的索引位置

大体解决方案:

利用vantUI框架引入indexBar索引栏

利用axios拿到后台城市数据,定义两个数据,一个为右边索引栏的字母数组(大写),一个为索引和城市的对象数组

先将右侧索引栏字母定义出来,遍历数据的拼音,取出首字母,排序,转大写

再定义第二个数组,做一个双for循环,先循环索引的字母,将字母以对象的形式插入到空数组中,再循环数据中拼音的首字母大写,若找出数据中的首字母大写与索引的字母一样的话就进行插入,以对象的形式插入到刚刚的数组中,最后用v-for遍历将数据渲染到桌面上

详细城市渲染步骤:

<template> <div> <!-- 循环右侧索引栏字母 --> <van-index-bar :index-list="indexList"> <!-- 建立一个空div进行循环,给索引和城市添加数据,渲染页面 --> <div v-for="(item,index) in cityIndex" :key="index"> <van-index-anchor :index="item.letter" /> <van-cell :title="item.name" /> </div> </van-index-bar> </div> </template> <script> import Vue from 'vue'; import instance1 from '@/utils/http' import { IndexBar, IndexAnchor,Cell } from 'vant'; Vue.use(IndexBar); Vue.use(IndexAnchor); Vue.use(Cell); export default { data () { return { cityIndex:[], //模拟:[{letter : A} , {name : "xxx"} , {name : "xxx"} , {letter : B} , {name : "xxx"} , {name : "xxx"} , {name : "xxx"}] indexList: [], //右侧索引栏(大写字母) } }, methods: { cities(data){ //先定义右侧索引栏 var a = data.map(item=>Array.from(item.pinyin).splice(0,1)) //遍历数据的拼音,截取出首字母 var UpperCase = Array.from(new Set(Array.from(a.toString()))).map(item=>item.toUpperCase()) //每个字母变为字符串,转一个总数组,去重,转数组,遍历转为大写字母 this.indexList = UpperCase.sort().slice(1) //排序,取出从第二个往后的字母 //定义模拟的城市对象 let cityarr = [] for(var i = 0; i < this.indexList.length; i++){ //循环字母 cityarr.push({letter:this.indexList[i]}) //先将字母以对象形式插入到数组中 for(var j = 0; j < data.length; j++){ //循环所有的数据 if(this.indexList[i] === data[j].pinyin.slice(0,1).toUpperCase()){ //找出索引字母与循环所有数据的首字母一样 cityarr.push({ //将城市名字以对象的形式插入数组中 name:data[j].name }) } } } this.cityIndex = cityarr }, }, created(){ instance1.get("/gateway?k=353128",{ headers:{ 'X-Host': 'mall.film-ticket.city.list' } }).then(res=>{ //写一个方法,将请求的数据给方法用 this.cities(res.data.data.cities) }) } } </script> <style lang="scss" scoped> </style>
最新回复(0)