My goal is to simplify the process of binding a form control to vuejs by creating a directive that handles all necessary events for tracking changes in a form field.
Rather than manually adding multiple event listeners like this:
<input type="text" name="firstName"
v-model="form.firstName.value"
@blur="form.firstName.onBlur"
@focus="form.firstName.onFocus"
@change="form.firstName.onChange"
[...]
/>
We can simply do this:
<input type="text" name="firstName" v-form-control="form.firstName" />
And let the directive handle everything behind the scenes.
However, I am struggling to figure out how to add a directive to the input element from within the FormControl
directive itself.
I considered trying something like this:
Vue.directive('form-control', {
bind: function(el: HTMLElement, binding: DirectiveBinding) {
const formControl: FormControl = binding.value;
el.addEventListener('input', (event) => {
formControl.updateValue(event.target.value);
});
},
});
But I feel like I am missing out on some of VueJS's capabilities by taking this approach. Manually attaching an input
event may not be as reliable as using the v-model
directive.
Is there a way to incorporate the original vue directives and events into an element from the bind
method of a directive?
Thank you for your assistance!