时间:2021-10-26 09:12:47 | 栏目:vue | 点击:次
效果展示:
代码展示:
<template> <div id="date_time_picker"> <van-button plain type="primary" @click="showPopFn()">点击选择日期</van-button> <van-field v-model="timeValue" placeholder="选择的日期结果" readonly /> <van-popup v-model="show" position="bottom" :style="{ height: '40%' }"> <van-datetime-picker v-model="currentDate" type="date" @change="changeFn()" @confirm="confirmFn()" @cancel="cancelFn()" /> </van-popup> </div> </template> <script> export default { data() { return { msg: '', currentDate: new Date(), changeDate: new Date(), show: false, // 用来显示弹出层 timeValue: '' } }, methods: { showPopFn() { this.show = true; }, showPopup() { this.show = true; }, 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 = true; }, timeFormat(time) { // 时间格式化 2019-09-08 let year = time.getFullYear(); let month = time.getMonth() + 1; let day = time.getDate(); return year + '年' + month + '月' + day + '日' } }, mounted() { this.timeFormat(new Date()); } } </script> <style> </style>
注意:如果是按需引入的话,记得在main.js里面引入相应的文件奥。
// main.js文件里面的部分代码 import {Button} from 'vant' import { DatetimePicker } from 'vant'; import { Popup } from 'vant'; import { Field } from 'vant'; Vue.use(Button) Vue.use(DatetimePicker) Vue.use(Popup) Vue.use(Field);
---------完。
补充知识:Vue + Vant DatetimePicker 日期选择 常见的日期限制(只允许选择当前月,整月选择)
安装Moment.js(Moment.js JavaScript 日期处理类库 http://momentjs.cn/)
npm install moment --save # npm
yarn add moment # Yarn
<van-datetime-picker class="datePick" v-model="currentDate" type="date" :min-date="minDate" :max-date="maxDate" readonly="readonly" @confirm="confirmDate" @cancel="cancelDate"/> mounted() { let dateLimit = new Date(); let year = date.getFullYear(); let month = date.getMonth()+1; let d = new Date(year, month, 0); //最大允许选择当前日期 this.maxDate = new Date(this.$moment(dateLimit).format('YYYY/MM/DD')); //最大允许选择当前日期+3个月 this.maxDate = new Date(this.$moment(dateLimit).add('3','M').format('YYYY/MM/DD')); //最小允许选择当前日期 this.minDate = new Date(this.$moment(dateLimit).format('YYYY/MM/DD')); //最小允许选择当前日期-3个月 this.minDate = new Date(this.$moment(dateLimit).subtract('3','M').format('YYYY/MM/DD'); //最小允许选择当前日期-3个月(当前月不算,减去三个整月2020/06/01----2020/09/22) this.minDate = new Date(this.$moment(dateLimit).subtract('3','M').format('YYYY/MM')+'/01'); //只允许选择当前月 let year = dateLimit.getFullYear(); let month = dateLimit.getMonth()+1; let d = new Date(year, month, 0); let enddate = d.getDate(); this.minDate = new Date(this.$moment(dateLimit).format('YYYY/MM/')+'01'); this.maxDate = new Date(this.$moment(dateLimit).format('YYYY/MM/')+ enddate); }
其中minData 和maxData 两两组合即可日期限制。