完整代码可以点击vue2 组件—js原生自定义日历组件实现方法 (jl1mall.com)查看
一、日历组件样式与基本需求
基本需求:封装一个日历组件,可以根据日期对应数据匹配对应阈值区间在当前日期下渲染不同颜色的短线。当天之后的日期显示为灰色,并设为无法点击的状态;进系统时默认当天的日期显示颜色,且当天日期下有个蓝色小点;若选择其他日期,小点位置一直保持在当天日期下,选择的日期显示为蓝色。
二、具体实现方法
1.html基本结构
使用table标签,添加表头thead和表项tbody。针对日历组件而言,星期数顺序固定不变,我们可以直接在thead中添加星期,不用动态生成。
<template >
<div class="main">
<table>
<thead>
<tr style="">
<td>日</td>
<td>一</td>
<td>二</td>
<td>三</td>
<td>四</td>
<td>五</td>
<td>六</td>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
</div>
</template>
本案例中的年份选择和日期选择受系统其他功能影响放在了组件外部。currentMonth代表当前月份,currentYear代表当前年份,clickDate是组件内发生点击日期事件后向父组件传值,以便联动其他系统功能。
<datePicker :currentMonth="currentMonth" :currentYear="currentYear" @clickDate="clickDate"></datePicker>
2.css样式部分
这一部分就不细说了,只是一些外部框架基本样式,可以根据自己的样式进行自定义修改。代码如下:
.main {
width: 100%;
height: 100%;
padding: 0.2rem 0.7rem;
table {
width: 100%;
text-align: center;
}
thead {
background: rgba(147, 210, 243, 0.5);
tr {
color: rgba(180, 253, 255, 1);
font-size: 1rem;
height: 2.33rem;
line-height: 1.25rem;
font-family: PingFangSC-regular;
}
}
}
.active {
background-color: #50508a90;
}
3.JavaScript实现细节
下面就进入了整个组件的关键部分—利用原生js实现自定义日历组件。
①获取当前年月日以及星期
getDate() {
const date = new Date()
const year = date.getFull