loading...
Cover image for Adding Dynamic HTML attributes with VUEJS

Adding Dynamic HTML attributes with VUEJS

seifsay3d profile image Seif Sayed ・1 min read

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

Posted on by:

seifsay3d profile

Seif Sayed

@seifsay3d

Hi there, I do frontend stuff @car2go. I like to talk about self development , awareness, tabs or spaces, vue or react, I love it all.

Discussion

markdown guide