借鉴链接: js 写点击上一月 下一月时候切换.
实现:
html:引用的是uview的日期控件
<template>
<view class="chooise-data">
<view class="yesterday" @click="prevDate()">
上一月
</view>
<view class="chooise-box">
<view class="date">
<view class="calendar">
<u-calendar v-model="show" ref="calendar" @change="change" :mode="mode" :btn-type="btnType"></u-calendar>
<view @click="showChange()">{{result}}</view>
</view>
<view class="date-icon">
<image src="../static/img/home/pop-date.png" mode=""></image>
</view>
</view>
</view>
<view class="tomorrow" @click="nextDate">
下一月
</view>
</view>
</template>
javascript 部分
<script>
export default {
data() {
return {
date: '',
show: false,
mode: 'date',
result: this.result,
btnType: 'primary',
};
},
beforeMount() {
this.result = this.getcurrentday()
},
methods: {
// 获取当前月期展示
getcurrentday() {
var date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
month = month < 10 ? "0" + month : month; //月小于10,加0
day = day < 10 ? "0" + day : day; //day小于10,加0
return `${year}-${month}`;
},
// 切换上一月
prevDate() {
let date = new Date(this.result); //获取当前的日期
let CurrentDate = "";
let year = date.getFullYear();
let month = (date.getMonth()) < 10 ? "0" + (date.getMonth()) : (date.getMonth()); //自动补0
//判断月份是否在当前年份
if (month < 1) {
CurrentDate = (year - 1) + "-" + "12"
} else {
CurrentDate = year + "-" + month
}
this.result = CurrentDate;
},
// 切换下一月
nextDate() {
let date = new Date(this.result);
let CurrentDate = "";
let year = date.getFullYear();
let month = (date.getMonth() + 1 + 1) < 10 ? "0" + (date.getMonth() + 1 + 1) : (date.getMonth() + 1 + 1);
//判断月份是否在当前年份
if (month > 12) {
CurrentDate = (year + 1) + "-" + "01"
} else {
CurrentDate = year + "-" + month
}
this.result = CurrentDate;
},
showChange(index) {
this.show = true; //是否显示控件
},
change(e) {
console.log(e)
let year = e.year;
let month = e.month;
month = month < 10 ? "0" + month : month;
this.result = `${year}-${month}`; //当前月期显示到页面组件
}
},
watch: {
chooisedate(val) {
this.$emit('result', this.result) //子组件传值
}
},
}
</script>