JAVASCRIPT

Create a Custom v-focus Directive

Extend Vue 3's capabilities by creating a custom directive, like v-focus, to automatically focus an input element when it appears on the page.

// main.js
import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

// Register a global custom directive called v-focus
app.directive('focus', {
  mounted(el) {
    el.focus(); // Focus the element when it's mounted
  },
  updated(el, binding) {
    if (binding.value) { // Only focus if the binding value is true
      el.focus();
    }
  }
});

app.mount('#app');

// components/MyComponent.vue
<template>
  <div>
    <label>Name: <input type="text" v-focus></label>
    <label>Email: <input type="email"></label>
    <label>Dynamic Focus: <input type="text" :v-focus="shouldFocus"></label>
    <button @click="shouldFocus = !shouldFocus">Toggle Dynamic Focus</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
const shouldFocus = ref(false);
</script>
How it works: This snippet shows how to create and use a custom Vue 3 directive. The `v-focus` directive automatically calls `focus()` on an input element when it's mounted. It also includes an `updated` hook to conditionally apply focus based on a dynamic binding value, providing more flexibility. Directives are ideal for low-level DOM interactions that don't directly map to component logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs