Apply directive from component to child

Viewed 1850

In Vue.js, if I have a component, such as custom-input, and I want to set focus from the parent class, can a directive from the parent be applied to the child?

<custom-input v-focus />

<div class='form-group'>
  <input :v-focus='vFocus'> // This doesn't work
</div>

<script type='text/javascript'>
  Vue.directive("focus", {
    inserted: function(el) {
      el.focus();
    }
  });
</script>
1 Answers

AFAIK, this is not possible out of box. There's a bit of magic behind the scenes that the template renderer does, that doesn't support this functionality. You could implement the functionality using the render function, but that could get quite complex.

The easier solution is to implement it by updating the component template and the directive.

here is a simple example http://jsfiddle.net/7tzLgp1c/

Vue.directive("focus", {
  inserted: function(el, binding, vnode) {
    if (binding.value !== undefined && binding.value !== false)
      el.focus();
  }
});

new Vue({
  el: "#app",
  components: {
    foo: {
      props: {
        focus: {
          default: undefined,
        }
      },
      template: '<div><input v-focus="focus"></div>'
    }
  }
})

template

<div id="app">
  <foo focus></foo>
  <foo></foo>
</div>

the trick here is to implement a condition inside the directive, since the directive inserted function runs on all components that have the directive. then instead of using the directive on the parent, you would pass it down

Related