3

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!

1 Answer 1

4

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}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! However, I'd like to use it in the part where I do new Vue() as in my question, is that possible?
Worked fine, just changed the usage to Vue.directive("click-outside", clickOutside);
where clickOutside is the imported file name
the directiveName is just an example, the directive could be imported anywhere in your vue app (main.js and the components

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.