1:组件化-将这个组件进行二次封装
<el-date-picker
v-model="dateRange"
type="datetimerange"
:editable="false"
:picker-options="pickerOptions"
:placeholder="$t('component.timeSelect.placeholder')"
:clearable="false"
@focus="timeFocus"
format="yyyy-MM-dd HH:mm"
/>
2:这里使用了composition-api
<script>
import { ref } from '@vue/composition-api'
// import 我是子组件 from '子组件地址'
export default {
// 组件名称
name: '',
props: {
disabledDate: {//默认只能选最近一个月的
type: Function,
default (time) {
const date = new Date(Date.now())
return time > date || time < new Date(date - 31 * 24 * 60 * 60 * 1000)
}
},
selectLimit: {//选择某一天的事件
type: Object,
default () {
return {}
}
},
timeFocus: {//获得焦点-点击时间选择器
type: Function,
default: () => { }
}
},
setup (props) {
const pickerOptions = {
disabledDate: props.disabledDate,
onPick: props.selectLimit.onPick
}
return {
pickerOptions
}
},
}
</script>
3:在业务中使用(记得引入)
<template>
<date-time-range-select
v-model="dateRange"
ref="timeSelector"
:disabledDate="disabledDate"
:selectLimit="selectLimit"
:timeFocus="timeFocus"
/>
</template>
<script>
import { ref } from '@vue/composition-api'
// import 我是子组件 from '子组件地址'
export default {
// 组件名称
name: '',
props: {},
setup () {
const choiceDate = ref('')
function disabledDate (time) {
const date = new Date(Date.now())
if (choiceDate.value) {
const res = 6 * 24 * 3600 * 1000;
// 当前日期 - res = 7天之前
const minTime = choiceDate.value - res
// 当前日期 + res = 7天之后
const maxTime = choiceDate.value + res
return (
time.getTime() < minTime ||
time.getTime() > maxTime ||
// 限制不能选择今天及以后
time.getTime() > getDayStartOrEnd(new Date(), "end") ||
time.getTime() < new Date(date - 31 * 24 * 60 * 60 * 1000)
)
}
return time > date || time < new Date(date - 31 * 24 * 60 * 60 * 1000) //不能选择今天以后以及一个月以前
}
const selectLimit = {
onPick: ({ maxDate, minDate }) => { // 最大时间 最小时间
choiceDate.value = minDate.getTime() // 当选一个日期时 就是最小日期
// // 如果选择了两个日期了,就把那个变量置空
if (maxDate) choiceDate.value = ''
}
}
function getDayStartOrEnd (time, type = "start") { // end 返回毫秒数
if (type == "start") {
return new Date(time).setHours(0, 0, 0, 0)
} else {
return new Date(time).setHours(23, 59, 59, 999);
}
}
function timeFocus () {
choiceDate.value = ''
}
return {
choiceDate,
disabledDate,
selectLimit,
timeFocus
}
},
}
</script>