All examples below use <v-app> as well, for clarity, but you can use v-focus on your own VueJS apps, without <v-app>.

v-focus

Automatically focus elements when they are inserted or when data changes

This is different than the HTML autofocus attribute which focuses elements on page load.

Examples

Basic usage, element is focused when inserted:

<v-app data='{"list":[""]}'>
	<article v-for="(item, i) in list">
		<input v-model="list[i]" @keyup.enter="list.push('')" v-focus>
	</article>

	<button @click="list.push('')">Add item</button>
</v-app>

You can also set focusabiity based on a data value. When the data value becomes truthy, the element will be focused. When the data value becomes falsy, it will be unfocused (if it's focused). Look at how easy this makes complex focus management:

<v-app data='{"list":[{}]}'>
	<article v-for="(item, i) in list">
		<input v-model="item.text" v-focus="item.active"
		       @keyup.enter="list.push({active: true})"
			   @focus="item.active = true"
			   @blur="item.active = false"
			   @keyup.backspace="list.splice(i, 1); (list[i-1] ?? list[i + 1] ?? {}).active = true"
			   @keyup.arrow-up="(list[i-1] ?? list[list.length - 1]).active = true"
			   @keyup.arrow-down="(list[i+1] ?? list[0]).active = true"
			   >
		<button @click="list.splice(i, 1); (list[i-1] ?? list[i + 1] ?? {}).active = true">x</button>
	</article>

	<button @click="list.push({active: true})">Add item</button>
</v-app>

These actions only happen when the value changes from truthy to falsy or vice versa, e.g. changing from "foo" to 1 has no effect, because both values are truthy.

Installation

If using <v-app>, all you need to do is include this JS file after it and you’re good:

<script src="https://mavue.mavo.io/v-focus/v-focus.js" type="module"></script>

If not using <v-app>, you can import the component individually:


				import VFocus from "https://mavue.mavo.io/v-focus/v-focus.js";

				// Then use it in your VueJS app
				createApp({
					/* ... */
					directives: {
						"focus": VFocus
					}
				}).mount("#app");