基于Vue实现timepicker

2020-06-13 10:31:40易采站长站整理

return {
current: this.mode,
hour: this.h,
minutes: this.m
}
},

正常情况下,如果时分不够两位数就要自动添加0,实现很简单的。刚开始直接判断是否小于10就添加。但是,“08”是小于10的,所以又自动添加0了。但是我觉得这里写得不好,还有改进的空间的。


//时分保证是两位数
fixHour: function() {
return (this.hour < 10 && this.hour.toString().indexOf(0) !== 0) ? "0" + this.hour : this.hour
}
fixMinutes: function() {
return (this.minutes < 10 && this.minutes.toString().indexOf(0) !== 0) ? "0" + this.minutes : this.minutes
},

再说说template里面的事吧。点击timepicker里面的时分改变组件的的current属性和透明度。这里显示数据就需要用到fixHour和fixMinutes了。


<div class="showtime">
<span @click="current = 0" :style="{opacity: current == 0 ? 1 : 0.7}">{{fixHour(hour)}}</span>
<span>:</span>
<span @click="current = 1" :style="{opacity: current == 1 ? 1 : 0.7}">{{fixMinutes(minutes)}}</span>
</div>

圆盘里的内容就靠v-for了。先定义好12个位置,然后遍历每个位置。里面的针就通过CSS3的旋转啦。一共360度,12个格,一小时60分钟,这么简单的数字知识就不继续说下去了,下面的乘法我相信各位是看得懂的。这里注意的是60,我们钟表没有60只有0啊,所以 ((5 * i) % 60 || “00”)。这里写得很有技巧。60%60是0。然后是||和&&的问题了(推荐两本书《你不知道的JavaScript》上中卷,内容跟《高级程序设计JS》也不怎么重复,值得看)。0强转为false,然后||就返回第二个操作数的值。


<template>
<div class="hourpicker">
<div class="selector" :style="selectorRotateAngle()"></div>
<span class="hourtxt" v-for="i in 12" :style="getHourStyle(i%12)" @click="current === 0 ? hour = i : minutes = ((5 * i) % 60 || '00')">{{current === 0 ? i : ((5 * i) % 60 || "00")}}</span>
</div>
</template>

methods: {
//分时针的样式
selectorRotateAngle: function(i) {
if(this.current === 0) {
return {
transform: 'rotateZ('+(this.hour * 30)+'deg)'
}
} else {
return {
transform: 'rotateZ('+(this.minutes * 6)+'deg)'
}
}
},
//12格样式
getHourStyle: function(i) {
var hasSelected = (this.current === 0 && this.hour % 12 === i)
|| (this.current === 1 && this.minutes % 60 == (i * 5)); //判断到底是哪个数值被选中
var styleObj = {
transform: 'translate(' + positions[i][0] + "px, " + positions[i][1] + "px)",