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?
<input :required="condition">
You don't need
<input :required="test ? true : false">
because if test is truthy you'll already get therequired
attribute, and if test is falsy you won't get the attribute. Thetrue : false
part is redundant, much like this...The simplest way of doing this binding, then, is
<input :required="condition">
Only if the test (or condition) can be misinterpreted would you need to do something else; in that case Syed's use of
!!
does the trick.<input :required="!!condition">
Simplest form:
Try: