vue获取当前的月份_vue根据选择的月份动态展示当前月份的每一天并展示每一天所对应的星期几...
时间: 2024-02-23 20:00:13 浏览: 66
vue根据数据动态展示页面
5星 · 资源好评率100%
可以通过Vue的computed属性来实现获取当前的月份,并通过v-for指令动态展示每一天,并通过JavaScript的Date对象获取每一天所对应的星期几。
以下是一个简单的实现示例:
```html
<template>
<div>
<select v-model="selectedMonth">
<option v-for="(month, index) in months" :key="index" :value="month">{{ month }}</option>
</select>
<table>
<thead>
<tr>
<th v-for="(day, index) in daysOfWeek" :key="index">{{ day }}</th>
</tr>
</thead>
<tbody>
<tr v-for="week in weeks" :key="week">
<td v-for="day in daysInMonth(week)" :key="day.date" :class="{ 'today': isToday(day.date) }">
{{ day.date }}
<br />
{{ day.dayOfWeek }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
selectedMonth: new Date().getMonth(),
months: [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
],
daysOfWeek: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
};
},
computed: {
currentYear() {
return new Date().getFullYear();
},
currentMonth() {
return this.selectedMonth;
},
weeks() {
const daysInMonth = this.daysInMonth();
const weekRows = [];
let currentWeek = [];
for (let i = 0; i < daysInMonth.length; i++) {
currentWeek.push(daysInMonth[i]);
if (daysInMonth[i].dayOfWeek === 'Sat' || i === daysInMonth.length - 1) {
weekRows.push(currentWeek);
currentWeek = [];
}
}
return weekRows;
}
},
methods: {
daysInMonth(week) {
const daysInMonth = [];
const year = this.currentYear;
const month = this.currentMonth;
const date = new Date(year, month, 1);
while (date.getMonth() === month || daysInMonth.length < 35) {
if (!week || date.getDay() === this.daysOfWeek.indexOf(week)) {
daysInMonth.push({
date: date.getDate(),
dayOfWeek: this.daysOfWeek[date.getDay()]
});
}
date.setDate(date.getDate() + 1);
}
return daysInMonth;
},
isToday(date) {
const today = new Date();
return this.currentYear === today.getFullYear() && this.currentMonth === today.getMonth() && date === today.getDate();
}
}
};
</script>
<style>
.today {
background-color: #f0f0f0;
}
</style>
```
在上面的示例中,我们首先定义了一个选项框,用户可以选择要展示的月份。然后,我们使用一个表格来展示当前月份的日期和星期几。我们使用computed属性来获取当前的年份、月份和星期几,并通过v-for指令动态展示每一天。我们还定义了一个方法来确定当前日期是否为今天,并将其标记为不同的颜色。
阅读全文