Search code examples
javascriptvue.jsvuejs2vue-component

Vue.js -Importing custom directive as ES6 Module


I have a rather specific question.

I'm using vue in my rails application through rails webpacker, to use vue components, I have to put a javascript pack tag in my layout and that references a javascript file that in turn renders the vue component, you can imagine that in total this approach has led me to make a lot of workarounds, but the one thing I still have left is a vue custom directive click-outside that I have had to add to each of my vue component generators, for example, here in filter-products.js

import Vue from "vue";
import filterProducts from "../../views/filter-products";
var element = document.getElementById("filter-products");
const props = JSON.parse(element.getAttribute("props"));

Vue.directive('click-outside', {
    bind: function(el, binding, vNode) {
    //bind logic
    },

    unbind: function(el, binding) {
    //unbind logic
    }
});

if (element != null) {
  new Vue({
    render: (h) => h(filterProducts, { props }),
  }).$mount(element);
}

the custom directive code is actually big, so what I have in mind but am not sure how to do is one of two things:

  • Have the bulk for that custom directive in an ES6 Module and import that here and just use it directly.
  • Create a prototype for Vue that includes this custom directive and import it instead of importing vue from "vue".

Is either of the approaches better? and how would I achieve them? thanks!


Solution

  • Create a folder named directives and for each directive create a file to make your code more organized and maintenable especially in team :

    import Vue from 'vue';
    
    const directiveName = {
        inserted: function(el, binding) {},
        update: function(el, binding) {},
    };
    
    export default directiveName;
    Vue.directive('directiveName', directiveName);//optional
    

    then import it in any component like :

    import directiveName from 'path-to-directives-folder/directives/directiveName'
    

    then use it as follows :

    data(){
      ...
    },
    directives:{directiveName}