效果图:
模拟数据源:
// date.js
// 模拟数据源,实际开发中可从后端接口中获取
export const days = [
{ daysDate: '2024-07-01', today: 1 },
{ daysDate: '2024-07-02', today: 2 },
{ daysDate: '2024-07-03', today: 3 },
{ daysDate: '2024-07-04', today: 4 },
{ daysDate: '2024-07-05', today: 5 },
{ daysDate: '2024-07-06', today: 6 },
{ daysDate: '2024-07-07', today: 7 },
{ daysDate: '2024-07-08', today: 1 },
{ daysDate: '2024-07-09', today: 2 },
{ daysDate: '2024-07-10', today: 3 },
{ daysDate: '2024-07-11', today: 4 },
{ daysDate: '2024-07-12', today: 5 },
{ daysDate: '2024-07-13', today: 6 },
{ daysDate: '2024-07-14', today: 7 },
{ daysDate: '2024-07-15', today: 1 },
{ daysDate: '2024-07-16', today: 2 },
{ daysDate: '2024-07-17', today: 3 },
{ daysDate: '2024-07-18', today: 4 },
{ daysDate: '2024-07-19', today: 5 },
{ daysDate: '2024-07-20', today: 6 },
{ daysDate: '2024-07-21', today: 7 },
{ daysDate: '2024-07-22', today: 1 },
{ daysDate: '2024-07-23', today: 2 },
{ daysDate: '2024-07-24', today: 3 },
{ daysDate: '2024-07-25', today: 4 },
{ daysDate: '2024-07-26', today: 5 },
{ daysDate: '2024-07-27', today: 6 },
{ daysDate: '2024-07-28', today: 7 },
{ daysDate: '2024-07-29', today: 1 },
{ daysDate: '2024-07-30', today: 2 },
{ daysDate: '2024-07-31', today: 3 }
]
vue 转换代码:
<template>
<div class="calendar-wrapper">
<div class="row weeks">
<div class="col" v-for="(item, index) in ['日', '一', '二', '三', '四', '五', '六']" :key="index">{{ item }}</div>
</div>
<div class="date-wrapper">
<div class="row" v-for="(row, rowIndex) in month" :key="rowIndex">
<div
v-for="(col, colIndex) in row"
:key="colIndex"
:class="['col', { 'is-weekend': col.today % 7 === 6 || col.today % 7 === 0, 'is-today': showDate(col) === '今天' }]"
>
{{ showDate(col) }}
</div>
</div>
</div>
</div>
</template>
<script setup>
import { computed, ref } from 'vue'
import { days } from './date'
let month = ref([])
let week = []
// 将日期一维数组按照每周转换成二维数组
days.forEach(i => {
if (i.today % 7 === 0 && week.length) {
month.value.push(week)
week = []
}
week.push(i)
})
// 最后一周的长度如果小于 7 就在数组后面进行填充,将长度填充到 7
if (week.length < 7) {
week = week.concat(new Array(7 - week.length).fill(''))
}
month.value.push(week)
// 第一周的长度如果小于 7 就在数组前面进行填充,将长度填充到 7
const week1 = month.value[0]
if (week1.length < 7) {
month.value[0] = new Array(7 - week1.length).fill('').concat(week1)
}
// 对页面中展示的日期进行格式化处理
const showDate = computed(() => {
return i => {
if (i && i.daysDate) {
if (i.daysDate.substr(-2) * 1 === new Date().getDate()) {
return '今天'
}
return i.daysDate.substr(-2) * 1
}
}
})
</script>
<style>
.row {
display: flex;
}
.col {
width: 40px;
height: 30px;
text-align: center;
}
.weeks .col {
font-weight: bold;
}
.is-weekend {
color: blue;
}
.is-today {
color: red;
}
</style>