LC Yoong
LC Yoong

Reputation: 1842

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.

Upvotes: 10

Views: 11436

Answers (4)

omarjebari
omarjebari

Reputation: 5499

I created a directory at /js/directives and added a file called AutoFocus.js with the following contents:

import Vue from 'vue';

const AutoFocus = {
  inserted(el) {
    el.focus();
  },
};

export default {
  AutoFocus,
};

// Make it available globally.
Vue.directive('focus', AutoFocus);

Note that, instead of 'inserted' above you may need to try 'bind' or 'update' depending on the approrpiate hook function for your scenario. I just replaced and tested with each until one worked! Then in my component i use the directive as follows:

<template>
    <input type="text" v-focus />
</template>
<script>
    import AutoFocus from '../../../directives/AutoFocus'; // Must point to your file!
    export default {
        directives: {
            AutoFocus,
        },
        // ... your other code here, eg props/methods etc
    }
</script>

Upvotes: 2

Tarun Bhartiya
Tarun Bhartiya

Reputation: 39

You can create a global directives file similar to how the global filters are created.

Create a directives.js

import Vue from 'vue'

Vue.directive('purple', function(el) {
    el.style.color = 'purple'
})

Import it into your main.js

Refer: How to add a bunch of global filters in Vue.js?

Upvotes: 3

Ludovic P&#233;net
Ludovic P&#233;net

Reputation: 1136

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.

Upvotes: 11

peaceman
peaceman

Reputation: 1721

Well I'm using Vue with Laravel and I'll give you what works for me.

In your app.js ( root file ) register components ( or directives ) as global Vue components.

So: // import Vue

Vue = require('vue');

Vue.component('my-custom-component', require('./directives/ComponentFileName.vue')

After this you'll be able to use it in html like so:

<my-custom-component></my-custom-component>

I'm sorry if I misunderstood your question.

Upvotes: -1

Related Questions