vue實現點擊、滑動右側字母對應各個城市


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

  

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM