@aw3r1se/vue-focus
v1.0.0
Published
Focus and unfocus vue-components
Maintainers
Readme
vue-focus
A tiny Vue 3 composable that tells you whether the user's interaction is focused inside a given element or outside of it. Useful for highlighting the active panel, closing dropdowns/menus on outside clicks, and similar UI states.
🔧 Installation
npm i @aw3r1se/vue-focus✏️ Usage
<script setup>
import { ref, watch } from 'vue';
import { useFocus } from '@aw3r1se/vue-focus';
const el = ref();
const { isFocused } = useFocus(el);
watch(isFocused, focused => {
focused ? markAsRed()
: markAsGrey();
});
</script>
<template>
<div ref="el">
...
</div>
</template>isFocused becomes true when an interaction starts inside el and false
when it starts anywhere outside of it.
📚 API
useFocus(targetRef, options?)
| Parameter | Type | Description |
| ----------- | -------------------------- | -------------------------------------------- |
| targetRef | Ref<HTMLElement \| null> | Template ref of the element to watch. |
| options | object | Optional configuration (see below). |
Options
| Option | Type | Default | Description |
| -------------- | ---------- | -------------------------------- | --------------------------------------------- |
| initialValue | boolean | false | Focus state before the first interaction. |
| events | string[] | ['mousedown', 'touchstart'] | Document events that update the focus state. |
Returns
| Property | Type | Description |
| ----------- | -------------- | ------------------------------------------------- |
| isFocused | Ref<boolean> | Reactive flag, true while the element is focused. |
The composable attaches the listeners on onMounted and removes them on
onUnmounted, so there is nothing to clean up manually.
🤝 Contributing
If you want to add or improve something - you are welcome
- Fork → Branch → Commit with feat: / fix: prefix
- Test locally
- Open a pull request
