vue 上下滑动选择小时
时间: 2023-09-29 16:08:32 浏览: 29
你可以使用 Vue.js 结合第三方库如 Better Scroll 实现上下滑动选择小时的功能。
首先,你需要在 Vue.js 中引入 Better Scroll 库,然后在组件内引入该库,初始化 Better Scroll 对象,并设置选项,如下所示:
```
import BScroll from 'better-scroll'
export default {
data () {
return {
hours: [], // 存储小时数据
selectedHour: '', // 存储当前选中的小时
bs: null // Better Scroll 对象
}
},
mounted () {
// 初始化 Better Scroll 对象
this.bs = new BScroll(this.$refs.wrapper, {
probeType: 3,
click: true
})
// 设置小时数据
for (let i = 0; i < 24; i++) {
this.hours.push(i.toString().padStart(2, '0'))
}
// 监听 Better Scroll 滚动事件
this.bs.on('scroll', (pos) => {
// 计算当前滚动到的位置与每个小时选项的位置的差值
let index = -Math.round(pos.y / 40)
// 更新选中的小时
this.selectedHour = this.hours[index]
})
}
}
```
在模板中,你可以通过 v-for 指令遍历小时选项,使用 ref 属性绑定 Better Scroll 容器元素,并绑定滚动事件:
```
<template>
<div class="hour-selector">
<div class="wrapper" ref="wrapper">
<ul>
<li v-for="hour in hours" :key="hour">{{ hour }}</li>
</ul>
</div>
<div class="selected-hour">{{ selectedHour }}</div>
</div>
</template>
<style>
.hour-selector {
position: relative;
margin-top: 20px;
height: 240px;
overflow: hidden;
}
.wrapper {
height: 200px;
overflow: hidden;
}
ul {
list-style: none;
padding: 0;
margin: 0;
height: 100%;
}
li {
height: 40px;
line-height: 40px;
text-align: center;
font-size: 16px;
color: #666;
border-bottom: 1px solid #ccc;
}
.selected-hour {
position: absolute;
top: 100px;
left: 0;
width: 100%;
text-align: center;
font-size: 28px;
font-weight: bold;
color: #333;
}
</style>
```
这样,就可以实现一个简单的上下滑动选择小时的功能了。当用户滑动 Better Scroll 容器时,根据当前滚动到的位置计算出选中的小时,并实时更新显示。