Home » vue » Vue – how to add custom directive with class define with `export default`

Vue – how to add custom directive with class define with `export default`

Posted by: admin November 26, 2021 Leave a comment

Questions:

Looking at the documentation for custom directives:
https://vuejs.org/v2/guide/custom-directive.html

The following example is given:

Vue.directive('pin', {
  bind: function (el, binding, vnode) {
    el.style.position = 'fixed'
    var s = (binding.arg == 'left' ? 'left' : 'top')
    el.style[s] = binding.value + 'px'
  }
})

new Vue({
  el: '#dynamicexample',
  data: function () {
    return {
      direction: 'left'
    }
  }
})

However, my class is structured with different syntax:

export default {
    name: 'dynamicexample',

In other words, I’m not using the new Vue keyword that is provided in the example.

Where and how do I add the directive in my code so it works?

The Vue.directive doesn’t work if I just paste it above export default { name: 'dynamicexample',. That just causes the app to fail without any warning or error.

Answers:

new Vue({
  el: '#demo',
  directives: {
    focus: {
      inserted: function (el) {
        el.focus()
      }
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <input type="text" v-focus />
</div>

You can try to create js file:

export const MyDirective {
  name: 'dynamicexample',
    /* your code */
}

then, in template where you use it :

import MyDirective from './directives/MyDirective.js';

export default {
    directives: {
       MyDirective
    }
    /* ... */
}

You can also use

Vue.directive('my-directive', MyDirective)

to declare it globally.