In VueJs Docs, https://vuejs.org/guide/custom-directive.html
I can easily create a custom directive using the native Vue.directive
method
My question is how would you be able to create a custom directive inside an export default {}
the same as when registering a component or prop:
components: {
Component1, Component2
},
methods: {
method1() {
// code here
}
},
In Vue 2.0, the primary code reuse and abstraction is components- however there may be cases where we need some low-level DOM access on plain elements, custom directives will still be useful here. A typical example would be focusing on an input element, like an input text.
But while component options are useful for abstraction and code reuse, custom directives are still one of the best ways to directly manipulate DOM elements. Like component and its lifecycle hooks, each Vue directive has its own hooks that trigger
There are two ways to define a custom directive in Vue. The first is the standard, which makes the directive available globally in the app: You can use this v-test directive anywhere in the app, but it doesn’t do anything right now, so we will add some functionality to it.
Vue also allows us to register our own custom directives aside the default set of directives that are shipped in core (v-show and v-model). In Vue 2.0, the primary code reuse and abstraction is components- however there may be cases where we need some low-level DOM access on plain elements, custom directives will still be useful here.
Here is a basical example about how to use directive in a component (*.vue file):
component/snippet.vue
<template>
<div id="snippet">
<code v-snippet>
{{snippet.code}}
</code>
</div>
</template>
<script>
import snippet from '../directive/snippet';
export default {
directives: {
snippet: snippet
}
}
</script>
directive/snippet.js
export default {
update: function (el) {
console.log('update');
}
}
For further information, You can check https://v2.vuejs.org/v2/guide/custom-directive.html (the Intro part).
export default {
components: {
Component1, Component2
},
methods: {
method1() {
// code here
}
},
directives: {
// create a directive named 'elementLog'
elementLog: {
inserted: function (el) {
console.log(el)
},
},
},
}
In the template write the name of the directive in kebab-case format and add 'v-'
<template>
<div>
<span v-element-log>One</span>
<span v-element-log>Two</span>
</div>
</template>
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