Now let's build the directive that accomplishes this:
const app = Vue.createApp({})
// Register a global custom directive called `v-focus`
app.directive('focus', {
// When the bound element is mounted into the DOM...
mounted(el) {
// Focus the element
el.focus()
}
})
If you want to register a directive locally instead, components also accept a directives
option:
directives: {
focus: {
// directive definition
mounted(el) {
el.focus()
}
}
}
Then in a template, you can use the new v-focus
attribute on any element, like this:
<input v-focus />