因为后台管理系统中经常会用到DatePicker 来作为常规查询条件中的时间范围,录入单据的创建时间范围,为了追加默认选项和一些常规配置例如:defalutTime来保证查询的时间范围是可以到指定日期之内的,快捷时间范围选项(一周内/一个月/三个月/半年/一年)等,为了将这些相关默认选项进行封装,将DatePicker组件进行默认封装,后续相关程序就可以大量减少代码。
封装如下:
<template> <el-date-picker v-model="timevalue1" :picker-options="pickerOptions" type="daterange" placeholder="选择日期时间" align="right" @change="changeTime"/> </template> <script> export default { name: ‘d2DateTimePicker‘, model: { prop: ‘timevalue‘, event: ‘change‘ }, props: { timevalue: { type: Array, required: true, default: () => { return this.timevalue1 } } }, data() { return { timevalue1: [new Date(), new Date(2021, 10, 1)], pickerOptions: { shortcuts: [{ text: ‘最近一周‘, onClick(picker) { const end = new Date() const start = new Date() start.setTime(start.getTime() - 3600 * 1000 * 24 * 7) picker.$emit(‘pick‘, [start, end]) } }, { text: ‘最近一个月‘, onClick(picker) { const end = new Date() const start = new Date() start.setTime(start.getTime() - 3600 * 1000 * 24 * 30) picker.$emit(‘pick‘, [start, end]) } }, { text: ‘最近三个月‘, onClick(picker) { const end = new Date() const start = new Date() start.setTime(start.getTime() - 3600 * 1000 * 24 * 90) picker.$emit(‘pick‘, [start, end]) } }] } } }, watch: { // timevalue: { // immediate: true, // // console.log(val, ‘time‘) // handler(val) { // this.$emit(‘change‘, val) // } // // }, timevalue1: { immediate: true, // console.log(val, ‘time‘) handler(newVal) { this.$emit(‘change‘, newVal) } } }, methods: { changeTime(val) { // var oval = this.moment(val).format(‘YYYY-MM-DD HH:mm:ss‘) // console.log(val) this.$emit(‘change‘, val) } } } </script>
外部使用示例:
<d2-date-time-picker v-model="searchDateRange" /> import d2DateTimePicker from ‘./d2DateTimePicker‘ export default { name: ‘HelloWorld‘, components: { d2DateTimePicker }, data() { return { searchDateRange: [], } },