[Vue] datepicker + 날짜 00:00 ~24:00 리스트 (date-fns)

suhanLee·2022년 7월 27일
0

vue

목록 보기
1/2

00:00
00:30
01:00
...(생략)
23:00
23:30

vuetify의 v-date-picker + 30분 단위 시간 리스트 선택
조합하기

$ npm install date-fns

DatePicker.vue

<template>
	<v-dialog v-model="show" max-width="290" persistent>
		<v-date-picker
			v-model="selectDate"
			locale="ko-kr"
			no-title
			:allowed-dates="val => allowedDate(val)"
		/>
		<v-list class="overflow-y-auto" height="200px">
			<v-divider />
			<v-list-item-group color="primary">
				<v-list-item
					v-for="(time, index) in timeList"
					:key="`${time}-${index}`"
					style="justify-content: center"
					ripple
					@click="selectTime = time"
				>
					{{ time }}
				</v-list-item>
			</v-list-item-group>
			<v-divider />
		</v-list>
		<v-list>
			<v-list-item style="justify-content: center">
				<v-btn class="primary--text" text width="100%" @click="confirmDate">
					확인
				</v-btn>
			</v-list-item>
		</v-list>
	</v-dialog>
</template>

<script>
	import { format } from 'date-fns';
	export default {
		props: {
			show: {
				type: Boolean,
				default: true,
			},
		},
		data() {
			return {
				selectDate: null,
				selectTime: null,
			};
		},
		computed: {
			timeList() {
				const date = new Date(9999, 1, 1);
				const rtrnList = [];
				for (let index = 0; index < 48; index++) {
					rtrnList.push(format(date, 'HH:mm'));
					date.setMinutes(date.getMinutes() + 30);
				}

				return rtrnList;
			},
		},
		methods: {
			allowedDate(val) {
				const now = new Date();
				const formatNow = format(now, 'yyyy-MM-dd');

				return val > formatNow;
			},
			confirmDate() {
				if (!this.selectDate || !this.selectTime) {
					alert('날짜와 시간을 선택해 주세요.');
					return;
				}

				this.$emit('pickerClose', {
					selectDate: this.selectDate,
					selectTime: this.selectTime,
				});
			},
		},
	};
</script>

<style></style>

MainView.vue

<template>
	<div>
    	<DatePicker :show="showDatePicker" @pickerClose="setDate" />
        {{reserveDate}}
    </div>
</template>
<script>
import DatePicker from '@/components/pop/DatePicker.vue';
import { format } from 'date-fns';
import { ko } from 'date-fns/locale';
export default {
	components: {
		DatePicker,
	},
    data() {
		return {
			showDatePicker: false,
            reserveDate:null,
		}
	},
    methods: {
    	setDate(date) {
			this.showDatePicker = false;
			const time = date.selectTime.split(':')[0];
			const minutes = date.selectTime.split(':')[1];
			const settingsDate = new Date(date.selectDate);
			settingsDate.setHours(time);
			settingsDate.setMinutes(minutes);
			this.reserveDate = format(settingsDate, 'yyyy-MM-dd HH:mm:ss EEEE', {
				locale: ko,
			});
		},
    }
    
}
</script>

0개의 댓글