Fabrizio Anichini
Fabrizio Anichini

Reputation: 81

Init JavaScript on vue.js

I'm trying to use flatpickr calendar option in a vue project. Essentially based on radio option I render different html content with the "v-if" conditional rendering.

The HTMl for choosing the timer is like that:

<div>
    <label>
       <input type="radio" name="timerType"
              @click="initCalendar"
              checked=""
              v-model="timer_type" 
              value="timer1"> TIMER 1 
     </label>
</div>
<div>
     <label class="form-check-label">
        <input type="radio"  name="timerType"
              v-model="timer_type"
              value="timer2">TIMER 2
     </label>
</div>

and the HTML where I render the timer is like that, I also apply the class and an ID for flatpickr calendar :

<div v-if="timer_type === 'timer1'">
    <input class="flatpickr flatpickr-input active" type="text" 
           placeholder="Select Date.."
           v-model="end_date"
           id="datetime" readonly="readonly">
</div>
<div v-else>
   <!--Other stuff-->
</div>

Now, for working properly flatpickr need the following code to init.

flatpickr("#datetime", {
     minDate: "today",
     enableTime: true,
     dateFormat: "F j, Y H:i",
});

Inside Vue I have some problem init the flatpickr obj. I have added the function initCalendar when the user click on the first radio. The function simply do the function showed above. It work the first time but I have some problem when an user click on the timer2 and again on the timer1. The problem I encounter is that I need to click 2 times before the function start to apply the calendar. The first time doesn't work at all. Maybe is the @click method wrong? Some suggestion?

Thanks in Advance!

Upvotes: 0

Views: 383

Answers (1)

Steven Spungin
Steven Spungin

Reputation: 29109

When the click occurs, the state is changed but element does not render immediately. Put your init code in a nextTick block.

this.$nextTick(()=>{
 flatpickr("#datetime", {
     minDate: "today",
     enableTime: true,
     dateFormat: "F j, Y H:i",
 });
});

If that does not work, put it in a setTimeout block and try various delays until one works.

If the timeout does not work, you might need to use v-show instead of v-if, and call your init from mounted().

Upvotes: 1

Related Questions