Is there any way that Vue custom directives can be implemented as individual files (ala Vue components .vue file) and be compiled in the root js file? (I'm using Webpack)
I tried the following on app.js but it's not recognised.
require('./directives/test.js');
Thanks in advance.
Vue. js allows you to register custom directives, essentially enabling you to teach Vue new tricks on how to map data changes to DOM behavior. You can register a global custom directive with the Vue. directive(id, definition) method, passing in a directive id followed by a definition object.
Vue Single-File Components (a.k.a. *.vue files, abbreviated as SFC) is a special file format that allows us to encapsulate the template, logic, and styling of a Vue component in a single file. Here's an example SFC: vue <script> export default { data() { return { greeting: 'Hello World!'
Common directives are v-if , v-for and v-model . The course covers all you need to know to be able to create your own, custom vue. js directives. In the course, we create three different directives to showcase the possibilities and power of custom vue.
A directive is only a class with a few well-defined methods. In JS, you can write something like :
export const MyDirective {
bind(el,binding,vnode) {
/* your code */
}
}
then, in the file where you use it :
<template>
<p v-app-my-directive:arg.modifier="value">Some Text</p>
</template>
<script>
import MyDirective from './directives/MyDirective.js';
export default {
directives: {
AppMyDirective: MyDirective
}
/* ... */
}
</script>
You can also use
Vue.directive('app-my-directive', MyDirective)
to declare it globally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With