为了给我自己做个笔记,同时给你们参考参考,废话不多说直接贴代码
<template>
<div class="wrapper" :class="[isWeb?'fixed-h':'']">
<!-- 全部地区 -->
<scroller class="city-box" @scroll="scrollHandler">
<template v-for="(item,i) in cityList">
<text :key="i" class="city-zimu" :ref="item.initial">{{item.initial}}</text>
<div v-for="citys in item.cityInfo" :key="citys.city" class="city-item" ref="alpitem">
<text>{{citys.city}}</text>
</div>
</template>
</scroller>
<!-- 侧边索引 -->
<div class="alphabet">
<template v-for="(item,i) in cityList">
<text :key="i" class="alphabet-item" :class="[item.initial==currentAlp?'alphabet-light':'']" @click="toLetter(item.initial,i)">{{item.initial}}</text>
</template>
</div>
</div>
</template>
<script>
const dom = weex.requireModule('dom')
import city from './city.js'
export default {
data() {
return {
cityList: null,//城市集合
currentAlp:'A',//侧边索引-高亮默认值
offsetTops:[],//各个字母距离顶部的距离
offsetY:0,//页面滚动的高度
isWeb:false,//是否是web端
};
},
watch: {
// 监听滚动的高度-获取侧边索引当前应高亮的字母
offsetY(now,old){
this.offsetTops && this.offsetTops.forEach((item,index)=>{
if(Math.abs(now)>this.offsetTops[this.offsetTops.length-1].height){
this.currentAlp = 'Z'
}else if(Math.abs(now)>=item.height && Math.abs(now)<=this.offsetTops[index+1].height){
this.currentAlp = item.alphabet
}
})
}
},
methods: {
// 获取字母标题和单个item的高度
getEleHeight(){
let self = this
this.$nextTick(function () {
let th = 0;
let ih = 0;
if(this.isWeb){
th = self.$refs.A[0].offsetHeight
ih = self.$refs.alpitem[0].offsetHeight
}else{
th = self.$refs.A[0].style.height
ih = self.$refs.alpitem[0].style.height
}
this.dealOffsetTop(th,ih)
})
},
// 获取每个字母距离顶部的距离
dealOffsetTop(titleH,itemH){
let h = 0;
this.cityList && this.cityList.forEach(Element => {
this.offsetTops.push({'height':h,'alphabet':Element.initial});
h = h + Number(Element.cityInfo.length * itemH) + Number(titleH) - 10;
});
},
// 侧边索引点击,列表滚动到相应位置
toLetter(alphabet,i) {
const el = this.$refs[alphabet][0];
dom.scrollToElement(el, {})
},
// 监听滚动高度,并赋值
scrollHandler: function(e) {
this.offsetY = e.contentOffset.y;
}
},
created() {
let _platform = WXEnvironment.platform//获取设备的platform
if(_platform=='Web'){
this.isWeb = true
}else{
this.isWeb = false
}
this.cityList = city.cityList();
this.getEleHeight()
}
};
</script>
<style scoped>
.wrapper{
width: 750px;
flex-direction: row;
}
.fixed-h{
height: 100vh;
}
.city-box{
width: 690px;
background-color: #e3e4e8
}
.city-item{
height: 80px;
padding:0 20px;
background-color: #fff;
justify-content: center;
border-bottom-width: 1px;
border-bottom-color: #e3e4e8;
}
.city-zimu{
height: 60px;
line-height: 60px;
font-size: 30px;
font-weight: bold;
padding:0 20px;
}
.alphabet{
width:60px;
background-color: transparent;
justify-content: center;
align-items: center;
}
.alphabet-item{
font-size: 26px;
color:#999;
padding-bottom: 8px;
padding-top:8px;
}
.alphabet-light{
font-size: 26px;
color: #000;
}
</style>