Search code examples
vuejs2flatpickr

Flatpickr not re-render with computed props (VueJs)


I have two flatpickers in my component. I have to change second date when the first was changed, but user can change second date manually.

<template>
    <default-field :field="field" :errors="errors">
        <template slot="field">

            <flatpickr
                v-model="dateStart"
                id="championshipDateStart"
                name="championshipDateStart"
                :placeholder="placeholder"
                :options="optionsStart"
                :value="dateStart"
            >
            </flatpickr>

            <flatpickr
                v-model="dateEnd"
                id="championshipDateEnd"
                name="championshipDateEnd"
                :placeholder="placeholder"
                :options="optionsEnd"
                :value="dateEndValue"
            >
            </flatpickr>

        </template>
    </default-field>
</template>

If user change first date, the second date should be first date + 3 days.

changeDateStart(event){
    this.dateEndValue = moment(new Date(this.dateStart)).add(3, 'day').format('YYYY-MM-DD');
}

I tried use computed props for re-render second flatpicker but nothing happens.

there are my computed props

computed: {
    placeholder(){
        return moment().format('YYYY-MM-DD');
    },

    optionsStart(){
        return {
            altInput: true,
            altFormat: "Y-m-d",
            allowInput: true,
            altInputClass: "w-1/3 mt-3 form-control form-input",
            onChange: this.changeDateStart()
        };
    },

    optionsEnd(){
        return {
            altInput: true,
            altFormat: "Y-m-d",
            allowInput: true,
            altInputClass: "w-1/3 mt-3 form-control form-input",
        };
    },

    dateEndValue:{
        get: function(){
           return this.dateEnd;
        },
        set: function(newDate){
            this.dateEnd = newDate;
        }
    }
}, 

The strangest thing is I see the changes in vue-devtools ( http://joxi.ru/nAynW7asggRNzr )

I use this lib ( https://www.npmjs.com/package/vue-flatpickr )


Solution

  • The way I would do it is with a watch on dateStart :

    watch : {
      dateStart (newV, oldV) {
        newDate = new Date(newV)
        this.dateEnd = newDate.setDate(newDate.getDate() + 3)
      }
    }
    

    No need for computed properties. If dateStart is changed, dateEnd will be changed. If dateEnd is changed, nothing else is changed.

    https://jsfiddle.net/3x491mwr/