Skip to main content
Category:

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 />

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook