Appearance
实现 日历日期选择 工具
分类:general | 标签:日历、日期、选择 月历选择日期查看星期
2.1 功能说明
月历选择日期查看星期
2.1.1 使用指南
功能说明
浏览月历、前后切换月份、选择某一天,查看该日是星期几及距离今天的天数。
使用场景
选日期、看节气、排期。
2.2 代码实现
2.2.1 组件结构
本工具是一个基于 Vue 3 <script setup> 语法的单文件组件(SFC),统一包裹在 ToolPageShell 组件内,由它提供页面标题、工具 ID、分类与「使用指南」插槽等通用外壳;核心业务逻辑(响应式状态、计算属性、事件处理函数)全部写在 <script setup> 中,输入/输出通过 el-input、el-button 等 Element Plus 组件与用户交互,所有数据均在浏览器本地处理,不会上传服务器。
2.2.2 核心逻辑概览
<script setup> 中定义的主要函数/方法:
buildCells()prev()next()isSel()select()
2.2.3 关键实现代码
以下是该工具的完整 <script setup> 实现(核心代码)。模板(<template>)与样式(<style>)已省略。
vue
import { ref } from 'vue'
import ToolPageShell from '@/components/ToolPageShell.vue'
const view = ref(new Date())
const selected = ref(null)
const today = new Date()
function buildCells() {
const y = view.value.getFullYear(), m = view.value.getMonth()
const first = new Date(y, m, 1).getDay()
const days = new Date(y, m + 1, 0).getDate()
const arr = []
for (let i = 0; i < first; i++) arr.push({ key: 'e' + i, day: 0 })
for (let d = 1; d <= days; d++) {
const dt = new Date(y, m, d)
arr.push({ key: d, day: d, date: dt, isToday: dt.toDateString() === today.toDateString() })
}
while (arr.length % 7) arr.push({ key: 'x' + arr.length, day: 0 })
return arr
}
const cells = ref(buildCells())
function prev() { view.value = new Date(view.value.getFullYear(), view.value.getMonth() - 1, 1); cells.value = buildCells() }
function next() { view.value = new Date(view.value.getFullYear(), view.value.getMonth() + 1, 1); cells.value = buildCells() }
function isSel(d) { return selected.value && d.date && d.date.toDateString() === selected.value.toDateString() }
const selInfo = ref('')
function select(d) {
selected.value = d.date
const diff = Math.round((d.date - new Date(today.getFullYear(), today.getMonth(), today.getDate())) / 86400000)
const wd = ['日', '一', '二', '三', '四', '五', '六'][d.date.getDay()]
selInfo.value = `${d.date.getFullYear()}-${String(d.date.getMonth() + 1).padStart(2, '0')}-${String(d.day).padStart(2, '0')} 星期${wd},距今天 ${diff} 天`
}2.3 效果截图
