JAVASCRIPT

Vue 3 Custom Directive for Auto-Focusing Elements

Create a reusable Vue 3 custom directive (`v-focus`) to automatically set focus on an input or other DOM element when it's rendered or updated in the DOM.

// src/main.js (or a separate directives file)
import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

// Register a global custom directive called `v-focus`
app.directive('focus', {
  // Called when the bound element's parent component and all its children
  // are mounted.
  mounted(el, binding) {
    if (binding.value !== false) { // Allow disabling focus with v-focus="false"
      el.focus();
    }
  },
  // Called before the parent component is updated
  updated(el, binding) {
    if (binding.value !== false && binding.oldValue === false) { // Focus only if it was enabled
      el.focus();
    }
  }
});

app.mount('#app');

// src/App.vue
<template>
  <div>
    <h1>Custom Focus Directive Example</h1>

    <label for="input1">Input 1 (Auto-focused on load):</label>
    <input id="input1" v-focus type="text" placeholder="I am auto-focused" />

    <br /><br />

    <label for="input2">Input 2 (Conditional focus):</label>
    <input id="input2" v-focus="shouldFocusInput2" type="text" placeholder="Focus me conditionally" />
    <button @click="shouldFocusInput2 = !shouldFocusInput2">
      Toggle Focus for Input 2 ({{ shouldFocusInput2 ? 'On' : 'Off' }})
    </button>

    <br /><br />

    <label for="input3">Input 3 (Normal input):</label>
    <input id="input3" type="text" placeholder="I am a normal input" />
  </div>
</template>

<script setup>
import { ref } from 'vue';
const shouldFocusInput2 = ref(false);
</script>
How it works: This snippet demonstrates how to create and use a custom global directive named `v-focus` in Vue 3. The directive automatically sets focus on an HTML element (like an input field) when the component it's attached to is mounted. It also includes logic to conditionally apply focus based on a reactive value, allowing for dynamic control over when an element should receive focus, showcasing the power and flexibility of custom directives for direct DOM manipulation.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs