Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Vue.js custom directive be implemented as individual files?

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.

like image 366
LC Yoong Avatar asked Feb 09 '17 14:02

LC Yoong


People also ask

What is custom directive in Vuejs?

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.

What are Vue single file components?

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!'

How many types of directives are available in Vue JS?

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.


1 Answers

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.

like image 59
Ludovic Pénet Avatar answered Sep 28 '22 01:09

Ludovic Pénet