前端之vue 封装自定义日历
warning:
这篇文章距离上次修改已过205天,其中的内容可能已经有所变动。
在Vue中封装一个自定义日历组件可以通过以下步骤实现:
- 创建一个新的Vue组件文件
Calendar.vue
。 - 定义组件模板,其中包括日历的布局和逻辑。
- 使用props接收外部传递的参数,如年份、月份等。
- 使用计算属性来生成日历的每一行和每一天。
- 可以添加事件处理函数来处理点击和其他交互。
以下是一个简单的自定义日历组件的示例代码:
<template>
<div class="calendar">
<table>
<thead>
<tr>
<th v-for="day in daysOfWeek" :key="day">{{ day }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(week, index) in calendar" :key="index">
<td v-for="day in week" :key="day.date" :class="{ 'current-day': isToday(day.date) }">
{{ day.day }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
props: {
year: {
type: Number,
required: true
},
month: {
type: Number,
required: true
}
},
data() {
return {
daysOfWeek: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
};
},
computed: {
calendar() {
let date = new Date(this.year, this.month - 1, 1);
let calendar = [];
let day = 1;
// Get first day of the month
let firstDayOfMonth = date.getDay();
// Get total days in the month
let totalDays = new Date(this.year, this.month, 0).getDate();
while (day <= totalDays) {
let week = [];
for (let i = 0; i < 7; i++) {
let dayOfMonth = day++;
week.push({
date: new Date(this.year, this.month - 1, dayOfMonth),
day: dayOfMonth
});
}
calendar.push(week);
}
return calendar;
}
},
methods: {
isToday(date) {
return this.isSameDate(date, new Date());
},
isSameDate(date1, date2) {
return (
date1.getFullYear() === date2.getFullYear() &&
date1.getMonth() === date2.getMonth() &&
date1.getDate() === date2.getDate()
);
}
}
};
</script>
<style scoped>
.calendar {
width: 100%;
}
.calendar table {
width: 100%;
border-collapse: collapse;
}
.calendar th {
text-align: center;
padding: 5px;
background-color: #f2f2f2;
}
.calendar td {
text-align: center;
padding: 5px;
border: 1px solid #ddd;
width:
评论已关闭