Earlier I had written an article on how we can create and use custom directives in Options API in Vue.js. In this article, we’ll see how we can define and use custom, global directives in the Composition API in Vue.js 3.
With the Composition API, we can also define various lifecycle methods for each of the element actions. For instance, we want to create a directive named v-large-font which would simply change the font size to 40px.
Here’s how we can define the directive without lifecycle methods:
//vLargeFont.js
const vLargeFont = (el) => {
el.style.fontSize = '40px'
}
export default vLargeFont
Code language: JavaScript (javascript)
And here’s how we can define the same with lifecycle methods. That is, we can change the font size whenever the directive is mounted with the component as follows:
//vLargeFont.js
const vLargeFont = {
mounted: (el) => {
el.style.fontSize = '40px'
},
}
export default vLargeFont
Code language: JavaScript (javascript)
You’d notice that in the previous example, we’re passing the element to the directive as a lifecycle method prop.
We can then import the directive in whichever component we want and use it directly:
//Home.vue
<template>
<div class="home">
<div v-large-font>This is some text</div>
</div>
</template>
<script setup>
import vLargeFont from './vLargeFont'
</script>
<style></style>
Code language: HTML, XML (xml)
If you have any suggestions or feedback, sound off in the comments below!