Skip to content

Latest commit

 

History

History

v-focus

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
id title type
v-focus
v-focus
directive

{% raw %}

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.

{% endraw %}