Last active
June 20, 2017 16:00
-
-
Save irrg/e5ccafc98a674c7b0b3adaff504bfa4f to your computer and use it in GitHub Desktop.
Vue 2, Nuxt.js/SSR friendly implementation of flatpickr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: Even simply
import
ing 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 triggermounted()
; 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: