Skip to content

Instantly share code, notes, and snippets.

@irrg
Last active June 20, 2017 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save irrg/e5ccafc98a674c7b0b3adaff504bfa4f to your computer and use it in GitHub Desktop.
Save irrg/e5ccafc98a674c7b0b3adaff504bfa4f to your computer and use it in GitHub Desktop.
Vue 2, Nuxt.js/SSR friendly implementation of flatpickr
<template>
<span v-if="datepickerVisible">
<input
type="text"
ref="datepickerInput"
class="form-input"
:placeholder="placeholder"
:value="value"
@input="updateValue($event.target.value)" />
</span>
</template>
<script type="text/javascript">
import 'flatpickr/dist/flatpickr.css';
export default {
props: [
'placeholder',
'minDate'
],
data() {
return {
datepickerVisible: false,
value: null,
calendar: null
}
},
watch: {
minDate () {
this.calendar.config.minDate = this.minDate
}
},
mounted() {
const Flatpickr = require('flatpickr')
const minDate = this.minDate ? this.minDate : new Date()
this.datepickerVisible = true
setTimeout(() => {
this.calendar = Flatpickr(this.$refs.datepickerInput, {
minDate: minDate
})
}, 0)
},
destroyed () {
this.calendar.destroy()
},
methods: {
updateValue: function (value) {
this.$refs.datepickerInput.value = value
this.$emit('input', value)
}
}
}
</script>
@irrg
Copy link
Author

irrg commented Jun 20, 2017

Note: Even simply importing Flatpickr while using Nuxt kept throwing me errors when rendering the page on the Server Side. So, this component (based partially on vue-bulma/datepicker#41 's suggestion) doesn't actually load Flatpickr unless mounting (Nuxt.js components don't trigger mounted(); I'm working under the assumption that this is default Vue SSR behavior).

This version also allows for dynamic updating of minDate, which is pretty key if you're capturing a start and an end date. I know that Flatpickr allows for the selection of a date range in a single picker, but I didn't love how that operated as an experience if the end date is optional.

This example (assuming data attributes start and end) allow you to reconfigure minDate on the 'end date' on the fly:

  placeholder="From"
  v-model="start" />

<Datepicker
  placeholder="To"
  v-model="end" 
  :minDate="start" />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment