Skip to content

Input Select Directives

v-input-select

A custom Vue directive that automatically selects the entire content of an input field when it receives focus, improving user experience when editing form fields.


Props (Binding Value)

None. This directive does not accept any binding values.


Slots

N/A (used as a directive, not a component).


Emits

None (directives do not emit events).


Functions

mounted(el)

  • Triggered when the directive is mounted to an element.
  • Uses nextTick to ensure DOM is fully rendered before adding event listeners.
  • Creates an onFocus handler that selects the entire content of the input field.
  • Adds the focus event listener to the element.
  • Stores the handler reference in a WeakMap for cleanup purposes.

unmounted(el)

  • Triggered when the directive is unmounted.
  • Retrieves the stored event handler from the WeakMap.
  • Removes the focus event listener from the element.
  • Deletes the reference from the WeakMap to prevent memory leaks.

Usage

vue
<template>
  <main>
    <!-- Apply to an input field -->
    <input v-input-select type="text" v-model="name" />
    
    <!-- Apply to a textarea -->
    <textarea v-input-select v-model="description"></textarea>
  </main>
</template>

<script setup>
import { ref } from 'vue';

const name = ref('John Doe');
const description = ref('Enter your description here');
</script>

Behavior

  • When the user focuses on an input with this directive applied, all text in the input will be selected.
  • This provides a better user experience for fields where users are likely to replace the entire content.
  • Only works on elements that have a select() method (like <input> and <textarea>).

Notes

  • Uses a WeakMap to store event handlers, which helps prevent memory leaks.
  • No visual styling is applied, only behavioral changes.
  • Useful for pre-filled fields that users are likely to replace entirely.
  • Improves user experience by saving the step of manually selecting all text.
  • Uses TypeScript type casting to ensure the element has the select() method.