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

  

 

 

转载于:https://www.cnblogs.com/chenlw/p/9720208.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值