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;
}
