Skip to content
Advertisement

How can I move directives from main.js into an external file Vue 3

I would like to have a clean main.js and for this I want to move the directives into an external file. That is, to do something like

//main.js
import directives from "./extensions-vue/directives";
app.directive(directives);

and in an external file

export default {
    myDirective: {
        mounted(el) {
            alert(el);
        },
    },
};

My version of course does not work, how to do it correctly

Advertisement

Answer

define them in a separate file like :

export default {
    'alert': {
        mounted(el) {
            alert(el);
        },
    },
  'log': {
        mounted(el) {
            console.log(el);
        },
    },
};

then import them in main.js and loop through them to declare them globally :

//main.js
import directives from "./extensions-vue/directives";

Object.keys(directives).forEach(key=>{ //Object.keys(directives) gives ["alert","log"]

   app.directive(key,directives[key])
//directive name--^    ^-------directive definition

})

Advertisement