VUE篇之日历组件
以下是一个简单的Vue日历组件示例,它允许用户选择一个日期并显示所选日期。
<template>
<div>
<h2>Simple Calendar</h2>
<p>Selected Date: {{ selectedDate }}</p>
<button @click="prevMonth">Prev Month</button>
<button @click="nextMonth">Next Month</button>
<div>
<div>Sun</div>
<div>Mon</div>
<div>Tue</div>
<div>Wed</div>
<div>Thu</div>
<div>Fri</div>
<div>Sat</div>
<div
v-for="day in calendar"
:key="day.date"
:class="{'selected': isSelected(day.date)}"
@click="selectDate(day.date)"
>
{{ day.day }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
selectedDate: null,
currentMonth: new Date(),
calendar: [],
};
},
created() {
this.buildCalendar();
},
methods: {
buildCalendar() {
const daysInMonth = new Date(this.currentMonth.getFullYear(), this.currentMonth.getMonth() + 1, 0).getDate();
this.calendar = [];
for (let day = 1; day <= daysInMonth; day++) {
this.calendar.push({
day: day,
date: new Date(this.currentMonth.getFullYear(), this.currentMonth.getMonth(), day),
});
}
},
prevMonth() {
this.currentMonth = new Date(this.currentMonth.setMonth(this.currentMonth.getMonth() - 1));
this.buildCalendar();
},
nextMonth() {
this.currentMonth = new Date(this.currentMonth.setMonth(this.currentMonth.getMonth() + 1));
this.buildCalendar();
},
selectDate(date) {
this.selectedDate = date;
},
isSelected(date) {
return this.selectedDate && this.selectedDate.toDateString() === date.toDateString();
},
},
};
</script>
<style scoped>
.selected {
background-color: blue;
color: white;
}
/* Add styles for the calendar layout */
</style>
这个日历组件使用Vue的数据驱动方法来构建动态日历。它允许用户点击前一个或下一个月份按钮来更新日历视图,并且可以选择一个日期,被选择的日期会被高亮显示。这个例子提供了一个简单的日历组件的基本功能,可以根据实际需求进行扩展和定制。
评论已关闭