前几天谢了一个类似于通讯录列表的城市列表选择页面,是运用vue 组件实现废话不多说先上效果图:
在这个页面中实现了城市 页面的布局,主要是实现了右边从A-Z的列表,下面是实现的代码
- 首先整个页面是上下设置了overflow:hidden属性,想要实现可以上下滑动的效果,我采用的是github上面 better-scroll组件,
2. 具体的实现方法如下:
首先是具体的布局
<div class="wrapper">
<ul class="content">
<li>...</li>
<li>...</li>
...
</ul>
<!-- you can put some other DOMs here, it won't affect the scrolling -->
</div>复制代码
其次是具体的引用方式
import BScroll from 'better-scroll'
const wrapper = document.querySelector('.wrapper')
const scroll = new BScroll(wrapper)复制代码
根据实际情况在项目中在mounted 这个钩子函数中执行
mounted () { this.scroll =new BScroll (this.$refs.wrapper) },复制代码
其中wrpper 是自己要滑动的内容区域,因此这样就可以实现页面上下滑动了
最后还剩下两个 功能就是 点击相应的字母页面滑动到对应自己的字母上, 这就用到better-scroll的另一个功能了 this.scroll.scrollToElement(elment)
scrollToElememt接受的是一个DOM元素,那我们又是如何获得每个传入的dom元素呢
首先我们可以给每一个A-Z设置一个点击事件,然后通过watch 来观察其变化, this.letter是电机的字母
watch:{ letter () { if(this.letter) { const elment=this.$refs[this.letter][0]; console.log(elment) this.scroll.scrollToElement(elment) } } }复制代码
然后通过
elment=this.$refs['Z'][0] 或者 elment=this.$refs['B'][0] 复制代码
来获得我们要跳转的某一个字母的城市区域, 这样就可以点击字母滑动到指定位置.
第二个功能就滑动A-Z到达指定位置
首先我的页面结构如下
<template> <div id="app"> <ListWrap :hotCities="hotCities" :cities="cities" :letter="letter" /> <CityList :cities="cities" @change="changeCity"/> </div></template>复制代码
ListWrap 是城市列表组件, CityList 是右侧A-Z组件
我计算的方式是 先要算出 A字符的距离顶部的offsetTop ,然后通过 e.touches[0].clientY来算出滑动截止手具体顶部的高度,然后双方相减 就可得知 A字母到达最后滑动的字母的距离,然后除以每一个高度 向下取整,Math.floor() 就可得知是是在A-Z字母数组中的下标,进而可得滑到那个字母的位置,下面是是代码和效果图
updated () { //获取A点距离最外层 (此时是#APP)的offsetTop值 this.startY=this.$refs["A"][0].offsetTop +66 }, methods:{ handleClick(e){ this.$emit("change",e.target.innerText) }, handleTocuchStart () { this.touchStatus=true; }, handleTocuchMove (e) { if(this.touchStatus) { if(this.tiemr) { clearTimeout(this.tiemr) } /**函数节流 */ this.tiemr=setTimeout(() => { //此时是获取手指移动结束后,到达顶部的高度 const touchY=e.touches[0].clientY; //向下取整,利用高度差除以每一个字母的高度来算出字母的下标 const index=Math.floor((touchY-this.startY)/21); if(index>=0&&index<this.letters.length){ this.$emit("change",this.letters[index]) } }, 16); } },复制代码
最后获得字母之后根据scrollToElemem.来滑动到相应的城市.
谢谢大家深知自己能力一般,写这些只为记录自己遇到的问题,有时候可能表述不清楚自己的意图,还请谅解,下面是自己写的demo的网址请大家指教: