Vue封装DateRangePicker组件流程详细介绍
骑上我心爱的小摩托 人气:0前言
日期选择器在实际使用中,可能会要求默认固定日期、回显日期或者是时间固定点(00:00:00到23:59:59)
一、封装el-date-picker
<template> <div> <el-date-picker @change="handleChange" v-model="dateValue" type="daterange" align="right" unlink-panels :clearable=false value-format="timestamp" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" :default-time="['00:00:00', '23:59:59']"> </el-date-picker> </div> </template> <script> export default { name: 'DateRangePicker', props: { defaultTimeRange: { type: Object, default() { return {}; } } }, data() { return { dateValue: '', pickerOptions: { shortcuts: [{ text: '最近一周', onClick(picker) { const end = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1); const start = new Date(new Date().toLocaleDateString()); ; start.setTime(start.getTime() - 3600 * 1000 * 24 * 7); picker.$emit('pick', [start, end]); } }, { text: '最近一个月', onClick(picker) { const end = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1); const start = new Date(new Date().toLocaleDateString()); ; start.setTime(start.getTime() - 3600 * 1000 * 24 * 30); picker.$emit('pick', [start, end]); } }, { text: '最近三个月', onClick(picker) { const end = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1); const start = new Date(new Date().toLocaleDateString()); ; start.setTime(start.getTime() - 3600 * 1000 * 24 * 90); picker.$emit('pick', [start, end]); } }] } }; }, mounted() { this.dateValue = [new Date(this.defaultTimeRange.from), new Date(this.defaultTimeRange.to)]; }, methods: { handleChange(time) { time = time || []; this.$emit('handleChange', {start_time: time[0], end_time: time[1]}); } } }; </script>
二、父组件中进行引用
父组件index.vue
<DateRangePicker @handleChange="handleTime" :default-time-range="defaultTimeRange"/>
<script> import { generateTodayDefaultTimeRange } from '@/utils/utils'; export default { data () { return { defaultTimeRange: { ...generateTodayDefaultTimeRange() } } } methods:{ handleTime(time) { //console.log(time)获取选择时间 } } } </script>
引用JSutils.js
// 今日默认时间范围 export function generateTodayDefaultTimeRange(date = new Date()) { const to = formatDateTime(new Date(date.getTime())); const from = formatDateTime(new Date(date.getTime())); return { from, to }; }
总结
- 综上所述,可见当前日期范围选择器默认时间是今天
default-time
设置时间点固定为起始的00:00:00到23:59:59
- 快捷项也设置成当前模式,自定义起始和结束时间文案
- 当前的获取时间格式为时间戳形式
value-format="timestamp"
加载全部内容