成果图
前期准备:
1、JSON文件:全国全国城市信息(下方链接地址是JSON文件)
2、封装组件
HTML 部分
<template>
<view class="main-Location">
<!-- 字母区域 -->
<view class="Location-Letter">
<view hover-class="Click-Latter" @tap="getLetter('ScrollTop')">*</view>
<view v-for="(l,i) in LatterName" :key="i" hover-class="Click-Latter" @tap="getLetter(l)"
:style="{'color': LetterId === l ? '#19BE6B' : '#000' }">{{l}}</view>
</view>
<scroll-view scroll-y="true" class="ynq-ScrollView" :scroll-into-view="LetterId">
<!-- 城市列表 -->
<view class="ynq-CityList">
<block v-for="(item,index) in CityList" :key="index">
<view class="ynq-CityLetter" :id="item.initial">{{item.initial}}</view>
<view class="ynq-CityLine">
<text @tap="getStorage(item_city.name)" v-for="(item_city,name_index) in item.list"
:key="name_index">{{item_city.name}}</text>
</view>
</block>
</view>
</scroll-view>
</view>
</template>
JavaScript 部分
<script>
var cityData = require('@/utils/city.json')
export default {
data() {
return {
CityName: '呼和浩特', // 默认城市
LatterName: ['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'],
CityList: cityData.city, //引用json数据
LetterId: '',
}
},
methods: {
// 获取定位点
getLetter(name) {
this.LetterId = name
uni.pageScrollTo({
selector: '#' + name,
duration: 300
})
}, // 跳转城市首字母定位
// 存储城市缓存(点击城市)
getStorage(Name) {
this.CityName = Name
uni.$emit('city', this.CityName) // 返回上一页并传数据
// 上一页在mounted用 uni.$on 接收
// uni.$on('city', (data) => {
// this.city = data;
// })
uni.navigateBack({
delta: 1 //返回上一页
})
},
// 或者可以存到storage中 在使用时再uni.getStorage
getStorage(Name) {
uni.setStorage({
key: 'City_Name',
data: Name
})
this.CityName = Name
//跳转返回
uni.navigateBack({
url: '/pages/index/index'
})
},
},
}
</script>
CSS部分
<style lang="scss">
.main-Location {
height: 100vh;
}
// 侧边字母选择栏
.Location-Letter {
position: fixed;
right: 5rpx;
top: 180rpx;
width: 30rpx;
z-index: 100;
view {
display: block;
width: 30rpx;
text-align: center;
height: 35rpx;
line-height: 35rpx;
font-size: 12px;
transition: ease .3s;
-webkit-transition: ease .3s;
}
}
// 城市列表
.ynq-CityList {
padding: 10px 0;
.ynq-CityLetter {
line-height: 30rpx;
height: 40rpx;
font-size: 16px;
border-bottom: 1px solid #f7f7f7;
padding-left: 10rpx;
color: #909090;
}
.ynq-CityLine {
background-color: #fff;
margin: 20rpx 0px;
text {
display: block;
line-height: 60rpx;
padding: 20rpx 30rpx;
font-size: 30rpx;
color: #767676;
border-bottom: 1px solid #f4f4f4;
}
}
}
</style>