DEV Community

Cover image for Adding Dynamic HTML attributes with VUEJS
Seif Sayed
Seif Sayed

Posted on

Adding Dynamic HTML attributes with VUEJS

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

Top comments (1)

jplindstrom profile image
Johan Lindstrom

s/Vola/voila/ :)