一、需求问题
在vue
项目开发中,我们在一些的场景中,需要应用到节流。节流的作用是规定一个单位时间,在这个单位时间内最多只能触发一次函数执行,如果这个单位时间内多次触发函数,只能有一次生效。对于节流的应用,比如在按钮点击事件、拖拽事件、onScroll
、计算鼠标移动距离等等。节流的实现方式有两种,第一种是利用时间戳、第二种是利用定时器。在这里,vue项目我采用的是定时器的方法。
二、需求分析
对于定时器的方式实现节流,需要先在data
中定义一个数据timer
,默认为null
。在methods
方法中,如果这个timer
存在,那么就通过clearTimeout
进行清除定时器。如果这个timer
不存在,那么就通过setTimeout
设置定时器,然后就可以在回调函数中写明相应需要执行的一些功能。
三、需求解决
1. 完整代码实例如下:
<template>
<ul class="list">
<li class="item" v-for="item of letters" :key="item" @click="handleLetterClick"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@tpuchend="handleTouchEnd"
:ref="item"
>{{item}}</li>
</ul>
</template>
<script>
export default {
name: 'CityAlphabet',
props: {
cities: Object
},
computed: {
letters () {
const letters = []
for (let i in this.cities) {
letters.push(i)
}
return letters
}
},
data () {
return {
touchStatus: false,
startY: 0,
timer: null
}
},
updated () {
this.startY = this.$refs['A'][0].offsetTop
},
methods: {
handleLetterClick (e) {
// console.log(e.target.innerText)
this.$emit('change', e.target.innerText)
},
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
const index = Math.floor((touchY - this.startY) / 20)
if (index >= 0 && index < this.letters.length) {
this.$emit('change', this.letters[index])
}
}, 20)
}
},
handleTouchEnd () {
this.touchStatus = false
}
}
}
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl'
.list
display: flex
flex-direction: column
justify-content: center
position: absolute
top: 1.58rem
right: 0
bottom: 0
width: .4rem
.item
line-height: .4rem
text-align: center
color: $bgColor
</style>