直接貼代碼
1.調用日期組件
<van-field v-model="timeValue" @click="showPopFn()" placeholder="請選擇到期日" readonly/>
<van-popup v-model="show" position="bottom" :style="{ height: '40%' }">
<van-datetime-picker
v-model="currentDate"
type="date"
:min-date="minDate"
:max-date="this.maxDate"
@change="changeFn()"
@confirm="confirmFn()"
@cancel="cancelFn()"
/>
</van-popup>
2.定義變量,最小時間就是當前時間
data() {
return {
value: '',
timeValue: '',
currentDate: new Date(),
changeDate: new Date(),
minDate: new Date(),
show: false, // 用來顯示彈出層
};
3. 通過計算屬性算出最大時間並返回
computed: {
maxDate(){
let curDate = (new Date()).getTime();
let one = 365 * 24 * 3600 * 1000;
let oneYear = curDate + one;
return new Date(oneYear);
}
},
4.method裏面寫對應的方法
methods: {
changeFn() { // 值變化是觸發
this.changeDate = this.currentDate // Tue Sep 08 2020 00:00:00 GMT+0800 (中國標準時間)
},
confirmFn() { // 確定按鈕
this.timeValue = this.timeFormat(this.currentDate);
this.show = false;
},
cancelFn(){
this.show = false;
},
timeFormat(time) { // 時間格式化 2019-09-08
let year = time.getFullYear();
let month = time.getMonth() + 1;
let day = time.getDate();
return year + '-' + month + '-' + day
},
},
5.mounted
mounted(){
this.timeFormat(new Date());
}
效果如下圖