JAVASCRIPT
Creating a Custom `v-focus` Directive in Vue 3
Learn how to create and register a custom directive in Vue 3, such as `v-focus`, to directly manipulate the DOM and enhance component functionality.
// main.js (or wherever your Vue app is created)
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
// Register a custom directive globally
app.directive('focus', {
mounted(el) {
el.focus();
}
});
app.mount('#app');
// --- Component usage example (e.g., in App.vue) ---
// <script setup>
// import { ref } from 'vue';
// const showInput = ref(false);
// </script>
//
// <template>
// <div>
// <h1>Custom Directive Example</h1>
// <button @click="showInput = !showInput">Toggle Input</button>
// <input v-if="showInput" v-focus type="text" placeholder="I will be focused!">
// </div>
// </template>
How it works: This snippet illustrates how to create and use a custom directive in Vue 3. Custom directives provide a way to abstract common low-level DOM manipulations. The `v-focus` directive is registered globally in `main.js` and focuses an input element when it's mounted. Directives expose several hook functions like `mounted`, `updated`, and `unmounted`, allowing control over the element's lifecycle.