需求:开始时时间大于结束时间,结束时间要大于等于结束时间两小时。
使用watch监听开始,结束时间
<template> <el-form label-width="100px"> <el-form-item label="开始时间"> <el-date-picker v-model="value1" type="datetime" placeholder="选择日期时间" align="right" > </el-date-picker> </el-form-item> <el-form-item label="结束时间"> <el-date-picker v-model="value2" type="datetime" placeholder="选择日期时间" align="right" > </el-date-picker> </el-form-item> </el-form> </template> <script> export default { data() { return { value1: new Date(), value2: new Date(new Date().getTime() + 1000 * 3600 * 2), }; }, watch: { value1: { handler(newTime, oldTime) { if (this.value2 != "" && this.value2 != null) { if (new Date(this.value2).getTime() <= newTime.getTime()) { this.value2 = new Date(newTime.getTime() + 1000 * 3600 * 2); this.value1 = newTime; } else { this.value1 = newTime; } } else { this.value2 = new Date(newTime.getTime() + 1000 * 3600 * 2); this.value1 = newTime; } }, immediate: true, }, value2: { handler(newTime, oldTime) { if (this.value1 != "" && this.value2 != null) { if (new Date(this.value1).getTime() >= newTime.getTime()) { this.value1 = new Date(newTime.getTime() - 1000 * 3600 * 2); this.value2 = newTime; } else { this.value2 = newTime; } } else { this.value1 = new Date(newTime.getTime() - 1000 * 3600 * 2); this.value2 = newTime; } }, immediate: true, }, }, }; </script>
immediate表示在watch中首次绑定的时候,是否执行handler方法,值为true则表示在watch中声明的时候,就立即执行handler方法,值为false,则和一般使用watch一样,在数据发生变化的时候才执行handler。
在handler方法中,不能以箭头函数定义,不然this不能指向vue实例。