获取当前年月 点击按钮切换年月
<div>{{ currentYear }}年{{ currentMonth }}月</div>
<button @click="prevMonth">上个月</button>
<button @click="nextMonth">下个月</button>
<button @click="prevYear">上一年</button>
<button @click="nextYear">下一年</button>
</div>
<script>
export default {
components: {},
data() {
return {
currentYear: 0,
currentMonth: 0,
};
},
computed: {},
mounted() {
this.getCurrentDate();
},
methods: {
// 获取当前年月
getCurrentDate() {
const currentDate = new Date();
this.currentYear = currentDate.getFullYear();
this.currentMonth = currentDate.getMonth() + 1;
},
// 上一月
prevMonth() {
if (this.currentMonth === 1) {
this.currentMonth = 12;
this.currentYear--;
} else {
this.currentMonth--;
}
},
// 下一月
nextMonth() {
if (this.currentMonth === 12) {
this.currentMonth = 1;
this.currentYear++;
} else {
this.currentMonth++;
}
},
// 上一年
prevYear() {
this.currentYear--;
},
// 下一年
nextYear() {
this.currentYear++;
},
},
};
</script>