TypeError: Cannot read property 'add' of undefined" Flatpickr & Vue.js

I'm trying to wrap flatpickr into a custom Vue component which should then should send dates to an eventHub, however I can't seems to get it to work. Somehow flatpickr can't find the input field (I think)

My wrapper component looks something like this:

<input type="text" id="flatpickr" placeholder="Select a range" />

const Flatpickr = require("flatpickr");

var defaultStart = new Date(new Date().setDate(new Date().getDate() - 10)).toISOString().slice(0, 10)
var defaultEnd = new Date().toISOString().slice(0, 10)

export default {
  name: 'DatePicker',
  props:['startDate', 'endDate'], // I don't really need this but I should pass data to all Children
  mounted() {
    new Flatpickr('#flatpickr', {
      dateFormat: "Y-m-d",
      mode: 'range',
      altInput: true, // Human Readable
      minDate: new Date().fp_incr(-60), // 60 days from today
      maxDate: defaultEnd,
      // defaultDate: [defaultStart, defaultEnd],
      // minDate: '2017-01-01', // 60 days from today
      // maxDate: '2017-05-05',
      // defaultDate: ["2017-02-02", "2017-04-04"],
      locale: { firstDayOfWeek: 1},
      onClose: function(selectedDates, dateStr, instance) {
        let startDate = selectedDates[0].toISOString().slice(0, 10);
        let endDate = selectedDates[1].toISOString().slice(0, 10);
        this.$emit('change', { startDate, endDate });  // emit to eventHub

I've also tried to use .class-name but nothing. What am I doing wrong?



Try making the following changes:

In the template...

<input type="text" ref="flatpickr" placeholder="Select a range" />

In the mounted() hook...

mounted() {
    var myInput = this.$refs.flatpickr
    new Flatpickr(myInput, { 

The Vue way of identifying elements in the template is by using "ref" (instead of "id") - and it's best to keep Vue happy because it does funky things with the template which may cause unexpected behaviours if you treat it as plain HTML. (It only looks like HTML but don't be fooled... the Vue template isn't HTML, and actually ends up getting compiled into a function.)

So, replace the input's id with a "ref" instead, and in your mounted() hook, get a variable reference to the input, and use that as the first parameter of your Flatpickr() call instead of an "#id".

JSFiddle: https://jsfiddle.net/CookieJon/7stotLrz/2/


Use this vue component instead.


npm install vue-flatpickr-component --save

It is dead simple to use.


    <flat-pickr v-model="date"></flat-pickr>

  import flatPickr from 'vue-flatpickr-component';
  import 'flatpickr/dist/flatpickr.css';

  export default {    
    data () {
      return {
        date: null,       
    components: {


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.