JAVASCRIPT
Create a Custom Directive for Toggling Visibility
Learn to build a reusable Vue 3 custom directive (`v-toggle-visibility`) that can hide or show elements based on a boolean expression, offering a declarative approach.
// src/directives/vToggleVisibility.js
export const vToggleVisibility = {
mounted(el, binding) {
el.__originalDisplay = el.style.display;
if (!binding.value) {
el.style.display = 'none';
}
},
updated(el, binding) {
if (binding.value) {
el.style.display = el.__originalDisplay;
} else {
el.style.display = 'none';
}
},
beforeUnmount(el) {
delete el.__originalDisplay;
}
};
// src/main.js (or global registration)
import { createApp } from 'vue';
import App from './App.vue';
import { vToggleVisibility } from './directives/vToggleVisibility';
const app = createApp(App);
app.directive('toggle-visibility', vToggleVisibility);
app.mount('#app');
// src/App.vue (Usage)
<template>
<div>
<h1>Custom Directive: v-toggle-visibility</h1>
<button @click="isVisible = !isVisible">
Toggle Element {{ isVisible ? 'Off' : 'On' }}
</button>
<div v-toggle-visibility="isVisible" style="background-color: lightgreen; padding: 20px; margin-top: 20px;">
This element's visibility is controlled by the custom directive.
</div>
<p>Always visible content.</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const isVisible = ref(true);
// No need to import the directive here if globally registered
// If not globally registered, you'd import and use it like:
// import { vToggleVisibility } from './directives/vToggleVisibility';
// const vToggleVisibilityDirective = vToggleVisibility;
</script>
How it works: This snippet demonstrates creating a custom Vue 3 directive, `v-toggle-visibility`, to control an element's CSS `display` property based on a boolean value. In `mounted`, it saves the original display style and hides the element if the initial value is false. In `updated`, it toggles the display property based on the new binding value. This provides a declarative and reusable way to manage element visibility without directly manipulating styles in component logic, promoting cleaner templates.