vue日历实现
Vue 日历组件实现方法
基础日历实现
使用第三方库如v-calendar快速搭建日历功能:
npm install v-calendar
引入并注册组件:
import VCalendar from 'v-calendar';
Vue.use(VCalendar);
模板中使用:
<template>
<v-calendar :attributes="attributes"/>
</template>
自定义日历组件
创建基础日历结构:
<template>
<div class="calendar">
<div class="header">
<button @click="prevMonth">上个月</button>
<h3>{{ currentMonth }}</h3>
<button @click="nextMonth">下个月</button>
</div>
<div class="days">
<div v-for="day in days" :key="day">{{ day }}</div>
</div>
<div class="dates">
<div
v-for="date in visibleDates"
:key="date.getTime()"
@click="selectDate(date)"
>
{{ date.getDate() }}
</div>
</div>
</div>
</template>
核心逻辑实现
日期计算逻辑:
data() {
return {
currentDate: new Date(),
days: ['日', '一', '二', '三', '四', '五', '六']
}
},
computed: {
currentMonth() {
return this.currentDate.toLocaleString('zh-CN', {
year: 'numeric',
month: 'long'
});
},
visibleDates() {
const dates = [];
const year = this.currentDate.getFullYear();
const month = this.currentDate.getMonth();
// 获取当月第一天
const firstDay = new Date(year, month, 1);
// 获取当月最后一天
const lastDay = new Date(year, month + 1, 0);
// 填充上月日期
const prevMonthDays = firstDay.getDay();
for (let i = prevMonthDays - 1; i >= 0; i--) {
dates.push(new Date(year, month, -i));
}
// 填充当月日期
for (let i = 1; i <= lastDay.getDate(); i++) {
dates.push(new Date(year, month, i));
}
// 填充下月日期
const nextMonthDays = 6 - lastDay.getDay();
for (let i = 1; i <= nextMonthDays; i++) {
dates.push(new Date(year, month + 1, i));
}
return dates;
}
}
事件处理
添加日期选择功能:
methods: {
prevMonth() {
this.currentDate = new Date(
this.currentDate.getFullYear(),
this.currentDate.getMonth() - 1,
1
);
},
nextMonth() {
this.currentDate = new Date(
this.currentDate.getFullYear(),
this.currentDate.getMonth() + 1,
1
);
},
selectDate(date) {
this.$emit('date-selected', date);
}
}
样式优化
基础日历样式:
.calendar {
width: 350px;
font-family: Arial;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
}
.days, .dates {
display: grid;
grid-template-columns: repeat(7, 1fr);
text-align: center;
}
.dates div {
padding: 10px;
cursor: pointer;
}
.dates div:hover {
background: #eee;
}
高级功能扩展
添加事件标记功能:
data() {
return {
events: [
{ date: new Date(2023, 5, 15), title: '会议' },
{ date: new Date(2023, 5, 20), title: '生日' }
]
}
},
methods: {
hasEvent(date) {
return this.events.some(event =>
event.date.toDateString() === date.toDateString()
);
}
}
模板中添加事件标记:
<div
v-for="date in visibleDates"
:key="date.getTime()"
:class="{ 'has-event': hasEvent(date) }"
>
{{ date.getDate() }}
</div>
响应式设计
添加媒体查询适应移动端:
@media (max-width: 600px) {
.calendar {
width: 100%;
}
.dates div {
padding: 5px;
}
}






