vue focus input
<template>
<div>
<input ref="myInput" v-focus />
</div>
</template>
<script>
export default {
directives: {
focus: {
// When the bound element is inserted into the DOM...
inserted(el) {
// Focus the element
el.focus()
}
}
}
}
</script>
Explanation:
In the template section, an
<input>
element is defined with aref
attribute set to "myInput" and a custom directivev-focus
is applied to it.In the script section, a Vue component is defined. Inside the component, a
directives
property is used to register a custom directive named "focus".The "focus" directive has a hook method named "inserted". This hook is called when the bound element is inserted into the DOM.
Inside the "inserted" hook, the passed element (
el
) is focused using theel.focus()
method.As a result, when the component is mounted, the input element with the ref "myInput" will receive focus, ensuring that it is focused when the page loads.