I imagine you are using the datepicker of element-ui
What I would do is:
- Define the properties
date_start
and date_end
as computed
- When changing its values, in
setter
execute ifSameDay
as method, not as property computed
.
- In the setter of
date_start
and date_end
fixed the value of this.form.dates[0]
and this.form.dates[1]
, since defining nested properties as computed is a problem. The getter of those two properties, in turn, returns the values of this.form.dates
.
- When executing
ifSameDay
, if the condition is met, set this.form.date_reincorporation
to the date you want, and set a property this.reincorporation_readonly
as true
to block the input.
- If the condition is not met, clean
this.form.date_reincorporation
and define this.reincorporation_readonly
as false
.
The input of the reincorporation date would be:
And you save yourself wrapping the parent in a v-if.
If your component today has the structure (I'm going to simplify a lot)
{
name: 'Licencias',
data() {
return {
form: {
dates: [new Date(), new Date()],
date_reincorporation: new Date()
}
}
},
methods: {
ifSameDay() {
const date_start = moment(this.form.dates[0]).format('DD/MM/YYYY');
const date_end = moment(this.form.dates[1]).format('DD/MM/YYYY');
return (date_start === date_end && date_start !== 'Invalid date') ? true : false;
},
}
};
With my suggestion, it would be:
{
name: 'Licencias',
data() {
return {
reincorporation_readonly: false,
form: {
dates: [new Date(), new Date()],
date_reincorporation: new Date()
}
}
},
computed: {
date_start: {
get() {
return this.form.dates[0];
},
set(date_start) {
this.form.dates[0] = date_start;
this.ifSameDay();
},
},
date_end: {
get() {
return this.form.dates[1];
},
set(date_start) {
this.form.dates[1] = date_end;
this.ifSameDay();
},
},
},
methods: {
ifSameDay() {
const date_start = moment(this.form.dates[0]).format('DD/MM/YYYY');
const date_end = moment(this.form.dates[1]).format('DD/MM/YYYY');
if (date_start === date_end && date_start !== 'Invalid date') {
this.form.date_reincorporation = date_end;
this.reincorporation_readonly = true;
}
},
}
};
In other words, the v-model
of the start date and end date point to date_start
and date_end
, which modify indirectly this.form.dates
. The funny thing is that by putting you getters and setters you can trigger the collateral effect of checking ifSameDay
in which you set the reincorporation date and leave the input as readonly. In this case, there is no v-if
in el-form-item
.
This is just a possible approach. You could also add a watcher to the properties, but that seems dirtier to me.
Finally, you could also force the reincorporation date by submitting without touching the rest of your code, but you would have to do two checks:
submitForm() {
this.form.date_reincorporation = this.ifSameDay? this.form.date[1] : this.form.date_reincorporation;
this.form.date_reincorporation = this.form.date_reincorporation? moment(this.form.date_reincorporation).format('YYYY-MM-DD HH:mm') : null;
}