Blog>
Snippets

Implementing a Focus Directive

Create a custom directive that can be used on form input elements to automatically focus on them when mounted.
Vue.directive('focus', {
  // When bind to the element, focus the element
  inserted: function (el) {
    el.focus();
  }
});
This directive is bound to Vue globally and uses the 'inserted' lifecycle hook which is called when the bound element is inserted into the DOM. This is where we can focus the element using el.focus().