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
JavaScript
x
4
1
//main.js
2
import directives from "./extensions-vue/directives";
3
app.directive(directives);
4
and in an external file
JavaScript
1
8
1
export default {
2
myDirective: {
3
mounted(el) {
4
alert(el);
5
},
6
},
7
};
8
My version of course does not work, how to do it correctly
Advertisement
Answer
define them in a separate file like :
JavaScript
1
13
13
1
export default {
2
'alert': {
3
mounted(el) {
4
alert(el);
5
},
6
},
7
'log': {
8
mounted(el) {
9
console.log(el);
10
},
11
},
12
};
13
then import them in main.js and loop through them to declare them globally :
JavaScript
1
11
11
1
//main.js
2
import directives from "./extensions-vue/directives";
3
4
Object.keys(directives).forEach(key=>{ //Object.keys(directives) gives ["alert","log"]
5
6
app.directive(key,directives[key])
7
//directive name--^ ^-------directive definition
8
9
})
10
11