饿了么日期控件月和日为空时候如何拼接才能满足格式要求?

项目为vue+element后台管理项目
某个详情界面,点进去之后有你年月日三个字段,三个字段又是独立存在得,任意一个都可以为空
如:{birhYear: '1995',birthMonth: '02',birthDay: '',} 或者另外两个也可以为空,基于此需求
看界面代码
进入界面年月日通过参数传递过来,回显到界面。
数据可以直接提交走下一个流程,也可以修改后提交。
只有年可以操作,操作后,将日期控件选择得时间回显到月和日,

<el-form-item label="出生年份" prop="birhYear">

<el-date-picker type="date" v-model="birthYear" format="yyyy 年" value-format="yyyy-MM-dd" placeholder="请选择出生年份"></el-date-picker>

</el-form-item>

<el-form-item label="出生月份" prop="birthMonth">

<el-input v-model="noteform.birthMonth" disabled></el-input>

</el-form-item>

<el-form-item label="出生日期" prop="birthDay">

<el-input v-model="noteform.birthDay" disabled></el-input>

</el-form-item>

js部分,有created生命周期加watch监听

 data() {

return {

birthYear: '',

noteform: {

birthDay: '',

birthMonth: '',

birthYear: '',

},

}

},

watch: {

birthYear: {

deep: true, //深度监听设置为 true

handler: function(newV, oldV) {

this.noteform.birthYear = newV.split('-')[0]

this.noteform.birthMonth = newV.split('-')[1] && newV.split('-')[1] != '00' ? newV.split('-')[1] : ''

this.noteform.birthDay = newV.split('-')[2] && newV.split('-')[2] != '00' ? newV.split('-')[2] : ''

},

},

},

created() {

this.noteform = Object.assign({}, this.noteform, this.$route.query)

let month = this.noteform.birthMonth ? this.noteform.birthMonth : '00'

let day = this.noteform.birthDay ? this.noteform.birthDay : '00'

if (this.noteform.birthYear) {

this.birthYear = this.noteform.birthYear + '-' + month + '-' + day

}

},

现在得问题就是在 created 中月和日为空时候,我拼接得 '00' 日期控件会错误理解
饿了么日期控件月和日为空时候如何拼接才能满足格式要求?
当它选择一月份时候,会自动变成上一年。
后来经测验拼接32时候,选择12月将会展示成下一年
1-31不能拼接,因为可以修改,修改时候可能选择1-31
月份也不能拼接00,会出现类似问题
求教各位大佬,我改如何处理这种情况,在月或日为空时候,如何去操作,既满足组件得value-format,又能正确展示年月日。因为项目已经投产所以希望最小得改动


回答:

一般使用 elemetnUI 也会使用 dayjs。这样的话就可以搭配 dayjs 返回个可用的日期了。

提供一段伪代码供你参考:

import dayjs from 'dayjs'

const formData = {

birthDay: '',

birthMonth: '',

birthYear: '2000',

}

let dateString = ''

if(!!formData.birthYear){

dateString = formData.birthYear

if(!!formData.birthMonth) dateString += formData.birthMonth

if(!!formData.birthMonth&&!!formData.birthDay) dateString += formData.birthDay

}

const birthYear = dayjs(dateString).format('YYYY-MM-DD')

console.log(birthYear)

// '2000-01-01'

如果不想引入 dayjs 的话也可以这样处理呀,只要你不去修改需要提交的表单数据就好了。

computed:{

datePickerValue(){

// 如果你默认值没有设为 `null` 的话就可以这样设置默认值

const { birthYear='2000', birthMonth='01', birthDay='01' } = this.formData;

return `${birthYear}-${birthMonth}-${birthDay}`

// 如果所有值都没有设置过的话就会返回 2000-01-01

// 设置过年月的话,就会变成 YYYY-MM-01

}

},


回答:

传给后端的日期和展示的日期分开不就行了,这样你想怎么显示都行,传给后端的始终就还是空的月和日

以上是 饿了么日期控件月和日为空时候如何拼接才能满足格式要求? 的全部内容, 来源链接: utcz.com/p/932959.html

回到顶部