DatePicker

DatePicker

출처: 문서

본문

날짜 입력을 위한 데이트 피커 컴포넌트예요. 날짜를 선택하는 UI가 필요할 때 기본적으로 쓰는 컴포넌트예요.

날짜 입력 (Enter Date)

'day' 단위로 측정하는 기본 날짜 선택기예요. 측정 단위는 type 속성으로 결정돼요. shortcuts 속성으로 빠른 옵션을 활성화할 수 있어요. 비활성화될 날짜는 함수인 disabledDate로 설정돼요.

<template>
  <div class="demo-date-picker">
    <div class="block">
      <span class="demonstration">Default</span>
      <el-date-picker
        v-model="value1"
        type="date"
        placeholder="Pick a day"
        size="large"
      />
    </div>
    <div class="block">
      <span class="demonstration">Picker with quick options</span>
      <el-date-picker
        v-model="value2"
        type="date"
        placeholder="Pick a day"
        :disabled-date="disabledDate"
        :shortcuts="shortcuts"
        size="large"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const size = ref('default')

const value1 = ref('')
const value2 = ref('')

const shortcuts = [
  {
    text: 'Today',
    value: new Date(),
  },
  {
    text: 'Yesterday',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: 'A week ago',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
      return date
    },
  },
]

const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}
</script>
.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 1.5rem 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
  min-width: 300px;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 1rem;
}

@media screen and (max-width: 768px) {
  .demo-date-picker .block {
    flex: 0 0 100%;
    padding: 1rem 0;
    min-width: auto;
    border-right: none;
    border-bottom: solid 1px var(--el-border-color);
  }

  .demo-date-picker .block:last-child {
    border-bottom: none;
  }
}

다른 측정 단위 (Other measurements)

표준 데이트 피커 컴포넌트를 확장해서 week, month, year, quarter 또는 여러 날짜(dates)를 선택할 수 있어요. type을 week, month, year, quarter, dates, years, months, quarters 중 하나로 설정하면 돼요.

날짜 범위 (Date Range)

날짜 범위 선택을 지원해요. 범위 모드에서는 기본적으로 왼쪽과 오른쪽 패널이 연결돼요. 두 패널이 현재 월을 독립적으로 전환하게 하려면 unlink-panels 속성을 사용할 수 있어요.

<template>
  <div class="demo-date-picker">
    <div class="block">
      <span class="demonstration">Default</span>
      <el-date-picker
        v-model="value1"
        type="daterange"
        range-separator="To"
        start-placeholder="Start date"
        end-placeholder="End date"
        size="large"
      />
    </div>
    <div class="block">
      <span class="demonstration">With quick options</span>
      <el-date-picker
        v-model="value2"
        type="daterange"
        range-separator="To"
        start-placeholder="Start date"
        end-placeholder="End date"
        :shortcuts="shortcuts"
        size="large"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const size = ref('default')

const value1 = ref('')
const value2 = ref('')

const shortcuts = [
  {
    text: 'Last week',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: 'Last month',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: 'Last 3 months',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]
</script>

월 범위 (Month Range)

월 범위 선택을 지원해요. type="monthrange"로 설정해요. 범위 모드에서는 기본적으로 왼쪽과 오른쪽 패널이 연결돼요. 두 패널이 현재 연도를 독립적으로 전환하게 하려면 unlink-panels 속성을 사용할 수 있어요.

연도 범위 (Year Range) 2.8.0

연도 범위 선택을 지원해요. type="yearrange"로 설정해요. 범위 모드에서는 기본적으로 왼쪽과 오른쪽 패널이 연결돼요. 두 패널이 연도를 독립적으로 전환하게 하려면 unlink-panels 속성을 사용할 수 있어요.

분기 범위 (Quarter Range) 2.14.5

분기 범위 선택을 지원해요. type="quarterrange"로 설정해요. 범위 모드에서는 기본적으로 왼쪽과 오른쪽 패널이 연결돼요. 두 패널이 연도를 독립적으로 전환하게 하려면 unlink-panels 속성을 사용할 수 있어요.

단일 패널 (Single Panel) 2.14.0

기본적으로 데이트 피커 범위는 두 개의 패널을 가져요. 하나의 패널만 원한다면 single-panel 속성을 설정하면 돼요. month range, year range, quarter range에 모두 적용할 수 있어요.

기본 값 (Default Value)

사용자가 날짜를 고르지 않았다면 기본적으로 오늘의 달력을 보여줘요. default-value를 사용해 다른 날짜를 설정할 수 있어요. 그 값은 new Date()로 파싱할 수 있어야 해요. type이 daterange라면 default-value는 왼쪽 달력을 설정해요.

날짜 포맷 (Date Formats)

format을 사용해 입력 상자에 표시되는 텍스트의 포맷을 제어하고, value-format을 사용해 바인딩 값의 포맷을 제어할 수 있어요. 기본적으로 컴포넌트는 Date 객체를 받고 내보내요. 사용 가능한 모든 Day.js 포맷 목록은 여기에서 확인할 수 있어요.

WARNING

대문자 사용에 주의하세요. 포맷 문자는 대소문자를 구분해요.

value-format을 사용하면 바인딩 값이 문자열이 되고, timestamp 형식(x 또는 X)을 사용하면 타임스탬프로 값이 설정돼요.

시작·종료 날짜의 기본 시간 (Default time for start date and end date)

날짜 범위를 선택할 때 시작일과 종료일의 시간 부분을 지정할 수 있어요. 기본적으로 시작일과 종료일의 시간 부분은 모두 00:00:00이에요. default-time을 설정하면 각각의 시간을 바꿀 수 있어요. 최대 두 개의 Date 객체로 이루어진 배열을 받아요. 첫 번째 문자열은 시작일의 시간을, 두 번째는 종료일의 시간을 설정해요.

<template>
  <el-date-picker
    v-model="value"
    type="daterange"
    start-placeholder="Start date"
    end-placeholder="End date"
    :default-time="defaultTime"
  />
</template>

<script setup lang="ts">
import { ref } from 'vue'

const value = ref('')
const defaultTime = ref([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
])
</script>

prefix 커스텀 내용 설정 (Set custom content of prefix)

prefix의 내용을 커스터마이즈할 수 있어요. 다른 .vue 파일에서 import 한 컴포넌트나 render 함수로 생성한 컴포넌트를 prefix-icon에 설정해요.

<template>
  <div class="demo-date-picker">
    <div class="block">
      <el-date-picker v-model="value1" type="date" placeholder="Pick a day" :prefix-icon="customPrefix" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { h, ref, shallowRef } from 'vue'

const value1 = ref('')

const customPrefix = shallowRef({
  render() {
    return h('p', 'pre')
  },
})
</script>

커스텀 내용 (Custom content)

셀의 내용을 커스터마이즈할 수 있어요. scoped-slot에서 셀 데이터를 얻을 수 있어요. 커스텀 내용 구조는 기본 구조와 일관돼야 해요. 그렇지 않으면 스타일 정렬이 어긋날 수 있어요.

<template>
  <div class="demo-date-picker">
    <div class="block">
      <p>Date</p>
      <el-date-picker
        v-model="value"
        type="date"
        placeholder="Pick a day"
      >
        <template #default="cell">
          <div class="cell" :class="{ current: cell.isCurrent }">
            <span class="text">{{ cell.text }}</span>
            <span v-if="isHoliday(cell)" class="holiday" />
          </div>
        </template>
      </el-date-picker>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const value = ref('2021-10-29')
const month = ref('')
const year = ref('')
const quarter = ref('')
const holidays = [
  '2021-10-01',
  '2021-10-02',
  '2021-10-03',
  '2021-10-04',
  '2021-10-05',
  '2021-10-06',
  '2021-10-07',
]

const isHoliday = ({ dayjs }) => {
  return holidays.includes(dayjs.format('YYYY-MM-DD'))
}
</script>
.demo-date-picker {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}

.demo-date-picker > * {
  margin: 0 !important;
}

.cell {
  height: 30px;
  padding: 3px 0;
  box-sizing: border-box;
}

.cell .text {
  width: 24px;
  height: 24px;
  display: block;
  margin: 0 auto;
  line-height: 24px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  border-radius: 50%;
}

.cell.current .text {
  background: #626aef;
  color: #fff;
}

.cell .holiday {
  position: absolute;
  width: 6px;
  height: 6px;
  background: var(--el-color-danger);
  border-radius: 50%;
  bottom: 0px;
  left: 50%;
  transform: translateX(-50%);
}

@media screen and (max-width: 768px) {
  .demo-date-picker {
    gap: 1.5rem;
  }
}

커스텀 아이콘 (Custom icon) 2.8.0

슬롯으로 커스텀 아이콘을 사용할 수 있어요. prev-month, next-month, prev-year, next-year 슬롯을 제공해요.

데이터 세부 사항은 다음을 참고하세요:

interface DateCell {
  column: number
  customClass: string | undefined
  disabled: boolean
  end: boolean
  inRange: boolean
  row: number
  selected: Dayjs | undefined
  isCurrent: boolean | undefined
  isSelected: boolean
  renderText: string | undefined
  start: boolean
  text: number
  timestamp: number
  date: Date
  dayjs: Dayjs
  type: 'normal' | 'today' | 'week' | 'next-month' | 'prev-month'
}

현지화 (Localization)

기본 로케일은 영어예요. 다른 언어를 사용해야 한다면 Internationalization 문서를 확인해 주세요. 날짜와 시간 로케일(월 이름, 한 주의 시작 요일 등)도 현지화 설정에 포함돼요.

API

Attributes

Name Description Type Default
model-value / v-model binding value, if it is an range picker, the length of the array should be 2 number / string / Date / array ''
readonly whether DatePicker is read only boolean false
disabled whether DatePicker is disabled boolean false
size size of Input enum —
editable whether the input is editable boolean true
clearable whether to show clear button boolean true
placeholder placeholder in non-range mode string ''
start-placeholder placeholder for the start date in range mode string —
end-placeholder placeholder for the end date in range mode string —
type type of the picker. quarter, quarters, and quarterrange are supported since 2.14.5 enum date
format format of the displayed value in the input box string see date formats YYYY-MM-DD
popper-class custom class name for DatePicker's dropdown string —
popper-style custom style for DatePicker's dropdown string / object —
popper-options Customized popper option see more at popper.js object {}
range-separator range separator string '-'
default-value optional, default date of the calendar object —
default-time optional, the time value to use when selecting date range object —
value-format optional, format of binding value. If not specified, the binding value will be a Date object string see date formats —
id same as id in native input string / array —
name same as name in native input string / array ''
unlink-panels unlink two date-panels in range-picker boolean false
single-panel 2.14.0 show only one panel in range-picker boolean false
prefix-icon custom prefix icon component. By default, if the value of type is TimeLikeType, the value is Clock, else is Calendar string / object ''
clear-icon custom clear icon component string / object CircleClose
validate-event whether to trigger form validation boolean true
disabled-date a function determining if a date is disabled with that date as its parameter. Should return a Boolean Function —
shortcuts an object array to set shortcut options array []
cell-class-name set custom className Function —
teleported whether date-picker dropdown is teleported to the body boolean true
empty-values 2.7.0 empty values of component, see config-provider array —
value-on-clear 2.7.0 clear return value, see config-provider string / number / boolean / Function —
fallback-placements 2.8.4 list of possible positions for Tooltip popper.js array ['bottom', 'top', 'right', 'left']
placement 2.8.4 position of dropdown Placement bottom
show-footer 2.10.5 whether to show footer where the date picker is one enum boolean true
show-confirm 2.11.0 whether to show the confirm button boolean true
show-week-number 2.10.3 show the week number besides the week boolean false
automatic-dropdown 2.11.4 this prop decides if the date picker panel pops up when the input is focused. (The default value will be set to false in version 3.0) boolean true

Events

Name Description Type
change triggers when user confirms the value or click outside Function
blur triggers when Input blurs Function
focus triggers when Input focuses Function
clear 2.7.7 triggers when a clear button is clicked Function
calendar-change triggers when the calendar selected date is changed. Only for range Function
panel-change triggers when the navigation button click. Function
visible-change triggers when the DatePicker's dropdown appears/disappears Function

Slots

Name Description
default custom cell content
range-separator custom range separator content
prev-month 2.8.0 prev month icon
next-month 2.8.0 next month icon
prev-year 2.8.0 prev year icon
next-year 2.8.0 next year icon

Exposes

Name Description Type
focus focus the DatePicker component Function
blur 2.8.7 blur the DatePicker component Function
handleOpen 2.2.16 open the DatePicker popper Function
handleClose 2.2.16 close the DatePicker popper Function

Type Declarations

import type { Options as PopperOptions } from '@popperjs/core'

type TimeLikeType = 'datetime' | 'datetimerange'

type Placement =
  | 'top'
  | 'top-start'
  | 'top-end'
  | 'bottom'
  | 'bottom-start'
  | 'bottom-end'
  | 'left'
  | 'left-start'
  | 'left-end'
  | 'right'
  | 'right-start'
  | 'right-end'

더 알아보기 (Learn more)