1.背景
项目需求收集用户信息,其中包含用户的出生年月,如果让用户自己输入,体验不太友好,所以要求使用滑动选择的方式。
草稿效果图:
2.实现大致思路(最后附上完整代码)
(1)组件从父元素获取开始和结束年份,使用循环获得年份的数组:
let yearList = [this.startYear - 2, this.startYear - 1];
for (let index = this.startYear; index <= this.endYear; index++) {
yearList.push(index);
}
yearList.push(this.endYear + 1, this.endYear + 2);
this.yearList = yearList;
这里,前后分别加了两个年份,以便拖动到最开始和最后的时候能选择。即:
(2)将数组显示到设置了可滑动的div中:
<div class="year" v-for="(year, index) in yearList" :key="index">
{ { year }}
</div>
这里就得到了可以滑动的年份,但是没有选中的样式以及渐变的效果。
(3)接着是实现滑动的时候选中
在设置了滑动的div中监听滑动:
<div class="year-box" @scroll.passive="scroll"></div>
passive使得滑动更平稳,监听函数:
scroll(e) {
// e.target.scrollHeight / this.yearListLength为每个选项高度
// e.target.scrollTop / (e.target.scrollHeight / this.yearListLength)判断滑动到哪一个选项
this.nowScrollYear = Math.round(
e.target.scrollTop / (e.target.scrollHeight / this.yearListLength)
);
this.year1 = th