I have a custom component. When using it, I'd like to be able to pass it a parameter determining whether it will autofocus one of its elements. As regular autofocus only works on page load, I have added a custom directive per the example here, and am registering it in the main file:
app.directive('focus', {
mounted: (el) => el.focus()
})
In the custom component, I've added a prop:
autofocus: {
type: Boolean,
default: false
},
Inside the component, it works if I pass the prop and use it in a regular attribute binding on the relevant template element inside the component, fx:
:autofocus="autofocus"
However, it doesn't work (the directive is not applied) if I try to use an attribute binding on the custom directive, like this:
:v-focus="autofocus"
If I hardcode the v-focus directive on the element with no attribute binding, the directive is applied as expected.
So, clearly you cannot just treat custom directives like attributes. But what would be the right way to conditionally apply the directive to a template element's attribute, then?
You should add the binding parameter to the directive definition :
app.directive('focus', {
mounted: (el, binding) => {
if(binding.value){
el.focus()
}
}
})
then pass the prop as directive binding value :
<input v-focus="autofocus"/>
directives are bound automatically without using :