需求:根据开始时间,通过填写阶段时长,自动填写结束时间,同时开始时间和节数时间可以手动输入
代码如下:
<el-form ref="ruleForm2" :rules="rules2" :model="formData" inline label-position="right" label-width="120px">
<el-form-item label="开始时间" prop="beginTime">
<el-date-picker
v-model="formData.beginTime"
v-elDateFormat
editable
value-format="timestamp"
type="date"
placeholder="请选择日期"
clearable
style="width: 180px"
@change="changeEndTime"
/>
</el-form-item>
<!-- 添加一个阶段时长 -->
<el-form-item label="阶段时长" prop="stageDuration">
<el-input v-model="formData.stageDuration" style="width: 180px" @blur="stageDurationBlur" />
<span class="span_style">(最小单位半月)</span>
</el-form-item>
<el-form-item label="结束时间" prop="endTime">
<el-date-picker
v-model="formData.endTime"
v-elDateFormat
editable
value-format="timestamp"
type="date"
placeholder="请选择日期"
clearable
style="width: 180px"
/>
</el-form-item>
</el-form>
changeEndTime(time) {
//这里是项目的一个判断 与主体逻辑无关
if (this.formData.stageNature == 'point') {
// this.formData.endTime = this.timestampToYYYYMMDD(time)
this.formData.endTime = time
} else {
this.calculateEndDate()
}
},
stageDurationBlur(e) {
if (this.formData.stageNature !== 'point' && this.formData.beginTime &&
e.target.value) {
this.calculateEndDate()
}
},
calculateEndDate() {
if (this.formData.beginTime && this.formData.stageDuration) {
const beginTime = new Date(this.formData.beginTime)
const duration = parseFloat(this.formData.stageDuration)
if (!isNaN(duration) && duration > 0) {
const daysToAdd = Math.floor(duration * 15) // 将输入的值乘以15天
const endTime = new Date(beginTime)
endTime.setDate(beginTime.getDate() + daysToAdd)
this.formData.endTime = endTime.getTime()
} else {
this.formData.endTime = ''
}
}
},
手动输入日期,默认回显日期功能,我这边后端参数需要的是时间戳,使用时需要看清楚后端需要的数据类型
watch: {
formData: {
handler(newValue, oldValue) {
if (newValue.beginTime && newValue.beginTime != '') {
// 判断有没有横杠 输入的日期 格式是 2024-07-15的,或者是20240715这种
if (typeof newValue.beginTime === 'string' && newValue.beginTime.indexOf('-') == -1) {
let str = newValue.beginTime
const positions = [4, 6]
const char = '-'
for (let i = positions.length - 1; i >= 0; i--) {
const position = positions[i]
str = str.substring(0, position) + char + str.substring(position)
}
this.formData.beginTime = str
}
} else {
this.formData.beginTime = ''
}
},
immediate: true,
deep: true
}
},
效果图: