用vue帮我写一个日期组件
时间: 2023-05-21 20:03:27 浏览: 87
当然可以,以下是一个简单的日期选择器组件的代码示例:
<template>
<div class="date-picker">
<input type="text" v-model="selectedDate" @click="showDatePicker" />
<div class="date-picker-overlay" v-if="show">
<div class="date-picker-header">
<button @click="previousMonth"><</button>
<span>{{ month }} {{ year }}</span>
<button @click="nextMonth">></button>
</div>
<div class="date-picker-body">
<div class="date-picker-row">
<div v-for="day in daysOfWeek" class="date-picker-cell">{{ day }}</div>
</div>
<div v-for="week in weeks" class="date-picker-row">
<div v-for="day in week" class="date-picker-cell" :class="{ 'date-picker-cell-selected': isSelected(day) }" @click="selectDate(day)">{{ day }}</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
show: false,
selectedDate: '',
year: new Date().getFullYear(),
month: new Date().toLocaleString('default', { month: 'long' }),
daysOfWeek: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
};
},
computed: {
weeks() {
const firstDayOfMonth = new Date(this.year, this.monthIndex, 1).getDay();
const daysInMonth = new Date(this.year, this.monthIndex + 1, 0).getDate();
const weeks = [[]];
let currentWeek = 0;
for (let i = 0; i < firstDayOfMonth; i++) {
weeks[currentWeek].push('');
}
for (let i = 1; i <= daysInMonth; i++) {
if (weeks[currentWeek].length === 7) {
currentWeek++;
weeks.push([]);
}
weeks[currentWeek].push(i);
}
return weeks;
},
monthIndex() {
return new Date(Date.parse(`${this.month} 1, ${this.year}`)).getMonth();
},
},
methods: {
showDatePicker() {
this.show = true;
},
hideDatePicker() {
this.show = false;
},
previousMonth() {
this.month = new Date(this.year, this.monthIndex - 1).toLocaleString('default', { month: 'long' });
this.year = new Date(this.year, this.monthIndex - 1).getFullYear();
},
nextMonth() {
this.month = new Date(this.year, this.monthIndex + 1).toLocaleString('default', { month: 'long' });
this.year = new Date(this.year, this.monthIndex + 1).getFullYear();
},
selectDate(day) {
this.selectedDate = `${this.year}-${this.monthIndex + 1}-${day}`;
this.hideDatePicker();
},
isSelected(day) {
return this.selectedDate === `${this.year}-${this.monthIndex + 1}-${day}`;
},
},
};
</script>
<style>
.date-picker {
position: relative;
}
.date-picker input {
padding: 5px;
border: 1px solid #ccc;
border-radius: 3px;
}
.date-picker-overlay {
position: absolute;
top: 100%;
left: 0;
z-index: 1;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 3px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
padding: 10px;
}
.date-picker-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.date-picker-body {
display: grid;
grid-template-columns: repeat(7, 1fr);
}
.date-picker-row {
display: flex;
}
.date-picker-cell {
flex: 1;
text-align: center;
padding: 5px;
}
.date-picker-cell-selected {
background-color: #ccc;
}
</style>
你可以将以上代码复制到你的 Vue 项目中,然后在需要使用日期选择器的地方使用该组件即可。
阅读全文