时间戳,一天
let oneDayTime = 86400000
function timeSec(type) {
//86400000为一天时间戳
let time = 86400000;
switch (type) {
case "1":
time = oneDayTime*3;
break;
case "2":
time = oneDayTime*31;
break;
case "3":
time = oneDayTime*365;
break;
case "4":
time = oneDayTime*365;
break;
default:
break;
}
return time;
}
想限制只能选日期间隔为一年,联合选择器样式不好改,使用俩单独的
有两个办法限制
1.一个在外层使用form通过表单验证控制,出现错误提示(由于是两个单独的组件,触发验证的方式又为单个失去焦点,所以俩组件无法实时更新)
2.用datepick自带的属性disabledDate ,为pick-options中的函数,在js中绑定函数,通过控制区间禁选不符合条件的日期,触发方式在每次选择时间时,可以实时更新无错误提示
1.form实现
form-html
<el-form ref="queryForm" :model="queryParams" inline>
<el-form-item
prop="startDate"
:rules="[
{ required: true, message: '请选择开始日期' },
{ validator: checkFinalPayTime, trigger: 'blur' },
]"
>
<el-date-picker
v-model="queryParams.startDate"
:clearable="false"
type="date"
:default-value="new Date()"
:disabledDate="disabledStartDate"
:value-format="YYYY - MM - DD"
placeholder="开始时间"
/>
</el-form-item>
<el-form-item
prop="endDate"
:rules="[
{ required: true, message: '请选择开始日期' },
{ validator: checkFinalPayTime, trigger: 'blur' },
]"
>
<el-date-picker
v-model="queryParams.endDate"
:clearable="false"
type="date"
:disabledDate="disabledEndDate"
:default-value="new Date()"
:value-format="YYYY - MM - DD"
placeholder="结束时间"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" icon="Search" @click="search"> 查询 </el-button>
<el-button icon="Refresh" @click="reset"> 重置 </el-button>
</el-form-item>
</el-form>
form-js
//form验证函数,触发后更改另一个验证错误不会消失
const checkFinalPayTime = (rule, value, callback) => {
const startDate = new Date(proxy.queryParams.startDate).getTime();
const endDate = new Date(proxy.queryParams.endDate).getTime();
console.log(startDate, endDate);
console.log(startDate + 31536000000 > endDate);
if (startDate + 31536000000 < endDate) {
return callback(new Error("起止日期不能超过一年"));
} else {
callback();
}
};
2.代码实现
disabledDate-html
<el-form ref="queryForm" :model="queryParams" inline>
<el-date-picker
v-model="queryParams.startDate"
:clearable="false"
type="date"
:default-value="new Date()"
:disabledDate="disabledStartDate"
:value-format="YYYY - MM - DD"
placeholder="开始时间"
/>
<el-date-picker
v-model="queryParams.endDate"
:clearable="false"
type="date"
:disabledDate="disabledEndDate"
:default-value="new Date()"
:value-format="YYYY - MM - DD"
placeholder="结束时间"
/>
</el-form>
disabledDate-js
const disabledStartDate = (time) => {
const endDate = new Date(proxy.queryParams.endDate);
//该函数会遍历整个页,time为该选择页中日期的时间,
//当return为false表示该日期可选,true则为不可选
return (
time.getTime() < endDate.getTime() - 31536000000 ||
time.getTime() > endDate.getTime()
);
};
const disabledEndDate = (time) => {
const startDate = new Date(proxy.queryParams.startDate);
//该函数会遍历整个页,time为该选择页中日期的时间,
//当return为false表示该日期可选,true则为不可选
return (
time.getTime() > startDate.getTime() + 31536000000 ||
time.getTime() < startDate.getTime()
);
};