I recently was working on a task where I had to consume a REST
endpoint which provides dynamic validation rules to that should be used to validate the form.
Long story short, I wanted to be able to dynamically set required
pattern
minlength
, etc. I thought okay, I am going to create a directive and use element.setAttribute
but then I remembered that Vuejs core team is awesome and must have done something for me.
v-bind directive to the rescue π
The v-bind
directive is so powerful as it provides you with attribute binding capabilities.
you are probably familiar with itβs shorthand version :
<input v-bind:src="imgSrc" />
<input :src="imgSrc" />
Now imagine we do not actually know which attribute we want to bind, maybe itβs the src
maybe it's the title
or maybe both.
v-bind
can actually taken object and Vola! you have a dynamically changing html attributes.
<input v-bind="validationRules" />
get validationRules () {
return {
required: true,
pattern: this.someMethodToGetPattern(),
src: false
}
}
Using this you can do so many cool stuff, I have only used it with form validation but I see myself using this more and more.
duck tip: vuejs automatically removes attributes that have their values set to false
Find more writings @duckfriend.dev
Top comments (1)
s/Vola/voila/ :)