<template>
<div class="calendar">
<h2>{{ currentMonth }} {{ currentYear }}</h2>
<div class="days">
<span v-for="day in daysOfWeek" :key="day">{{ day }}</span>
</div>
<div class="dates">
<span v-for="date in dates" :key="date.date" :class="{ 'other-month': !date.isCurrentMonth }">
{{ date.day }}
</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentMonth: '',
currentYear: '',
daysOfWeek: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
dates: []
};
},
mounted() {
this.updateCalendar(new Date());
},
methods: {
updateCalendar(date) {
const year = date.getFullYear();
const month = date.getMonth();
this.currentMonth = new Intl.DateTimeFormat('en-US', { month: 'long' }).format(date);
this.currentYear = year;
// Get the first day of the month
const firstDayOfMonth = new Date(year, month, 1).getDay();
// Get the last day of the month
const lastDateOfMonth = new Date(year, month + 1, 0).getDate();
// Get the last day of the previous month
const lastDayOfPrevMonth = new Date(year, month, 0).getDate();
// Create an array to hold all dates
this.dates = [];
// Add the dates from the previous month
for (let i = firstDayOfMonth; i > 0; i--) {
this.dates.push({
day: lastDayOfPrevMonth - i + 1,
date: new Date(year, month - 1, lastDayOfPrevMonth - i + 1),
isCurrentMonth: false
});
}
// Add the dates from the current month
for (let i = 1; i <= lastDateOfMonth; i++) {
this.dates.push({
day: i,
date: new Date(year, month, i),
isCurrentMonth: true
});
}
// Add the dates from the next month
const daysInNextMonth = 42 - this.dates.length;
for (let i = 1; i <= daysInNextMonth; i++) {
this.dates.push({
day: i,
date: new Date(year, month + 1, i),
isCurrentMonth: false
});
}
}
}
};
</script>
<style scoped>
.calendar {
font-family: Arial, sans-serif;
width: 300px;
margin: 0 auto;
}
.days span,
.dates span {
display: inline-block;
width: 14.28%;
text-align: center;
}
.other-month {
color: #ccc;
}
</style>
这段代码实现了一个简单的 Vue 日历组件。以下是关键部分的解释:
模板部分 (<template>
):
v-for
指令循环显示一周中的每一天(星期日到星期六)。v-for
指令循环显示当月的所有日期,包括前一个月和下一个月的部分日期。脚本部分 (<script>
):
data()
返回一个对象,包含当前月份、年份、一周中的每一天以及所有日期。mounted()
钩子函数在组件挂载时调用 updateCalendar
方法更新日历。updateCalendar(date)
方法根据给定的日期生成日历数据:dates
数组中,并标记是否为当前月份的日期。样式部分 (<style scoped>
):
.other-month
类来设置非当前月份日期的颜色为灰色。这个示例展示了如何使用 Vue.js 创建一个交互式日历组件。
上一篇:vue request
下一篇:vue2项目创建
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站