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
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
})
Well they doesn't really offer a good option for it in the docs, I use it like this:
in directives/index.js:
export const focusDirective = {
mounted(el) {
el.focus();
}};
in main.js:
import { focusDirective } from './directives'; // import all wanted directives
const app = createApp(App);
app.directive('focus', focusDirective );
I feel like its simpler and more intuitive then the other answer, But i'd prefer a way for my diretive file to register those directives globally without the need to handle it on main.js
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.