# Improving Your Application's Features with Vue Custom Directives

**Vue.js** is a popular JavaScript framework that provides a powerful and flexible way to build user interfaces. It comes with built-in directives like v-model and v-if which allow you to create a two-way binding on a form input element and control the visibility of elements based on a condition, respectively.

**What are Vue Custom Directives?**

Vue custom directives are a way to extend the behavior of Vue.js by providing a way to apply custom JavaScript logic to HTML elements in the DOM. Directives are used to modify the behavior of the element to which they are applied.

---

**Usage of Custom Directives**

Custom directives can be used whenever you need to add custom behavior or functionality to your Vue.js application that is not provided by built-in directives or other Vue.js features. For example:

* Change the position, background color and size of an element or add event listeners to an element
    
* Add a focus outline to elements that can be focused by keyboard navigation
    
* Animate the appearance or disappearance of an element or animate changes to the position or size of an element.
    
* Create a custom dropdown menu or a custom input field with validation.
    

**How to Create Custom Directives in Vue.js**

Creating custom directives in Vue.js is a straightforward process. A custom directive is defined as a JavaScript object with a set of properties and methods that define its behavior.

---

### **Get started**

Let's create a custom directive that will trigger an event when clicked outside of the component in Vue 3's Composition API.

```javascript
import { createApp } from "vue"
import App from "./App.vue"

const app = createApp(App)

app.directive("click-outside", {
    mounted(el, binding, vnode) {
        const vm = vnode.context
        const callback = binding.value
        el.clickOutsideEvent = function(event) {
            if (!(el === event.target || el.contains(event.target))) {
                return callback.call(vm, event)
            }
        }
        document.body.addEventListener("click", el.clickOutsideEvent)
    },
    unmounted(el) {
        document.body.removeEventListener("click", el.clickOutsideEvent)
    },
})

app.mount("#app")
```

Here, `app.directive()` method is used to register a new directive with the name `click-outside` globally. The `beforeMount` function is called when the directive is first applied to an element and the `unmounted` function is called when the directive is removed from the element.

**Parameters**:

* **el:** This parameter refers to the element to which the directive is attached.
    
* **binding**: This parameter contains information about the directive's arguments and modifiers if any.
    
* **vnode**: This parameter is the virtual node representing the element to which the directive is attached.
    

---

### **Usage**

To use the **click-outside** directive in your template, you can simply add it to an element using the `v-click-outside` syntax:

```javascript
<script setup>
    import { ref } from "vue"
    const showPopup = ref(false)

    function hidePopup() {
        showPopup.value = false
    }
</script>

<template>
    <div v-click-outside="hidePopup" class="popover-container">
        <button @click="showPopup=true">Click me</button>
        <div class="popover-content" :class="{ 'show': showPopup }">
            <p>Popover content goes here</p>
        </div>
    </div>
</template>

<style scoped>
    /* Button styles */
    .button {
        background-color: #4CAF50;
        border: none;
        color: white;
        padding: 12px 24px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.2s ease-out;
    }

    /* Popover container styles */
    .popover-container {
        position: relative;
        display: inline-block;
    }

    /* Popover content styles */
    .popover-content {
        position: absolute;
        top: 120%;
        left: 50%;
        transform: translateX(-50%);
        width: 200px;
        background-color: #fff;
        border: 1px solid #ccc;
        border-radius: 4px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        padding: 10px;
        font-size: 14px;
        line-height: 1.5;
        z-index: 999;
        visibility: hidden;
        opacity: 0;
        transition: visibility 0s, opacity 0.2s linear;
    }

    /* Show popover when showPopup is true */
    .popover-content.show {
        visibility: visible;
        opacity: 1;
    }
</style>
```

In the example, the `v-clickoutside` directive is attached to the `div` element that contains the popup content. When the user clicks outside of this element, the `hidePopup` method is called to hide the popup. The `showPopup` data property is used to show the visibility of the popup content.

---

### **Example**

Check out the preview of custom vue click outside directive here or access the source base in GitHub [vue-custom-directive](https://github.com/razn12/vue-clickoutside-directive).

%[https://codepen.io/razn12/pen/ZEMBEbb] 

---

### **Reference**

[https://vuejs.org/guide/reusability/custom-directives.html#object-literals](https://vuejs.org/guide/reusability/custom-directives.html#object-literals)

---

### **Conclusion**

Custom directives in Vue are a powerful tool for extending the behavior of HTML elements and creating reusable code. With a bit of creativity and skill, you can use them to make your Vue applications more powerful, efficient, and elegant.

👏👏 By coming this far I hope you can use the vue custom directive in your project. So, I suggest you give your a try on your project and enjoy it!

Feel free to share your thoughts and opinions and leave me a comment if you have any problems or questions.
