今天在做查询功能时,条件中有一个起止年月,需要默认设定为上个月的值
<el-date-picker
v-model="value1"
type="monthrange"
range-separator="至"
value-format="yyyy-MM-01 HH:mm:ss"
start-placeholder="开始月份"
end-placeholder="结束月份">
</el-date-picker>
由于组件设定了value-format,指定了绑定值的格式,所以想当然的使用此格式设定默认值
mounted () {
this.value1 = ['2023-01-01 00:00:00', '2023-03-31 23:59:59']
},
watch() {
'value1' (val) {
console.log(`-----watch 监听------ value1`, val)
},
}
结果设定无效果,虽然值正确,但是组件中没有显示。
经过多种尝试,看API等,最终使用下面的设定方法,搞定了页面正确显示的问题。
mounted () {
const beforeDate = new Date()
beforeDate.setMonth(beforeDate.getMonth() - 1)
beforeDate.setDate(1)
beforeDate.setHours(0, 0, 0, 0)
const endDate = new Date()
endDate.setMonth(beforeDate.getMonth())
endDate.setDate(28)
endDate.setHours(23, 59, 59, 999)
this.value1 = [beforeDate, endDate]
},
watch() {
'value1' (val) {
console.log(`-----watch 监听------ value1`, val)
},
}
此时虽然页面显示正确,但是组件默认获取的值却不再是value-format样式的字符串格式,变成了日期对象,手动选择后又恢复到value-format样式的字符串格式。
造成默认值搜索时传递数据格式错误,最后手工在watch 中对值进行监听,格式化。
不知道是不是我用法有错误,还是这个组件有BUG。
