1.字母组件给父组件传递当前点击的字母值
@click="handleLetterClick" //绑定事件
handleLetterClick (e) { //向上传递参数
this.$emit('change',e.target.innerText)
},
2.父组件接收字母组件传递的值
<city-alphabet :cities="cities" @change="handleLetterChange"></city-alphabet>
//先定义一个空的接收
data () {
return {
letter:''
}
},
//将接收的值传给letter
handleLetterChange (letter){
this.letter = letter;
}
//传给对应的城市组件
<city-list :letter="letter"></city-list>
//这里需要better-scroll插件
import Bscroll from 'better-scroll'
//绑定需要插件的地方
mounted () {
this.scroll = new Bscroll(this.$refs.wrapper);
},
//城市组件监听letter的变化,实现跳转
watch:{
letter() {
if(this.letter){
const element=this.$refs[this.letter][0];
this.scroll.scrollToElement(element);
}
}
}
3.实现滑动跳转城市
//绑定滑动事件
<li v-for="item of letters" :key="item" :ref="item"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
@click="handleLetterClick"
>{{item}}</li>
//用计算属性来存储(cities)letters
computed:{
letters(){
const letters=[];
for(let i in this.cities){
letters.push(i);
}
return letters;
}
},
//data
data (){
return {
touchStatus:false,
startY:0,
timer:null
}
},
//为了让性能提高,startY,就计算一次
updated(){
//A元素对应顶部的高度
this.startY=this.$refs['A'][0].offsetTop;
},
handleTouchStart(){
this.touchStatus=true;
},
handleTouchMove(e){
if(this.touchStatus){
// 函数节流
if(this.timer){
clearTimeout(this.timer)
}
this.timer=setTimeout(() => {
// 当前手指到最顶部的高度-头部高度
const touchY = e.touches[0].clientY - 79;
//(touchY - startY)手指到A顶部的高度/20(每个字母的高度)=当前第几个字母
const index = Math.floor((touchY - this.startY) / 20);
if(index >= 0 && index < this.letters.length){
this.$emit('change',this.letters[index]);
}
},16);
}
},
handleTouchEnd(){
this.touchStatus=false;
}