VueJS conditionally add an attribute for an element

Don Smythe picture Don Smythe · Mar 18, 2017 · Viewed 91.4k times · Source

In VueJS we can add or remove a DOM element using v-if:

<button v-if="isRequired">Important Button</button>

but is there a way to add / remove attributes of a dom element eg for the following conditionally set the required attribute:

Username: <input type="text" name="username" required>

by something similar to:

Username: <input type="text" name="username" v-if="name.required" required>

Any ideas?

Answer

cymruu picture cymruu · Mar 18, 2017

Try:

<input :required="test ? true : false">