Search code examples
javascriptvue.jsvuejs2flatpickr

vue2 flatpickr directive approach not working on mobile


I want to use a simple directive to use flatpickr with vue.js, like the author suggest here:

import Flatpickr from "flatpickr";
import Vue from "vue";

// <input type="text" v-flatpickr="{'enableTime': true}"

Vue.directive("flatpickr", {
    bind: (el, binding) => {
        el._flatpickr = new Flatpickr(el, binding.value);
    },
    unbind: el => el._flatpickr.destroy()
});

I created a simple fiddle to see if this works. On the desktop it's all fine, but when switching to mobile-mode (via chrome dev tools) and press "run" the needed input isn't created. Only the hidden input is created (see via inspect).

Anyone knows what this could cause this?


Solution

  • try {
        self.input.parentNode.insertBefore(self.mobileInput, self.input.nextSibling);
    } catch (e) {
        //
    }
    

    self.input.parentNode === null

    It also returns null if the node has just been created and is not yet attached to the tree.

    Use inserted instead bind

    Vue.component('greeting', {
      template: '<div><input type="text" v-flatpickr="{}" /></div>'
    });
    
    Vue.directive('flatpickr', {
      inserted: (el, binding) => {
        el._flatpickr = new flatpickr(el, binding.value)
      },
      unbind: el => el._flatpickr.destroy()
    })
    
    var vm = new Vue({
      el: '#app'
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
    <script src="https://cdn.rawgit.com/chmln/flatpickr/v3.0.5-1/dist/flatpickr.js"></script>
    <link href="https://cdn.rawgit.com/chmln/flatpickr/v3.0.5-1/dist/flatpickr.css" rel="stylesheet"/>
    
    <div id="app">
      <greeting></greeting>
    </div>