In VueJS we can add or remove a DOM element using v-if:
but is there a wa
It's notable to understand that if you'd like to conditionally add attributes you can also add a dynamic declaration:
<input v-bind="attrs" />
where attrs is declared as an object:
data() {
return {
attrs: {
required: true,
type: "text"
}
}
}
Which will result in:
<input required type="text"/>
Ideal in cases with multiple attributes.
Conditional rendering of attributes changed in Vue 3. To omit an attribute use null
or undefined
.
Vue 2:
<div :attr="false">
Result: <div>
<div :attr="null">
Result: <div>
Vue 3:
<div :attr="false">
Result: <div attr="false">
<div :attr="null">
Result: <div>
Try:
<input :required="test ? true : false">
Simplest form:
<input :required="test"> // if true
<input :required="!test"> // if false
<input :required="!!test"> // test ? true : false
<input :required="condition">
You don't need <input :required="test ? true : false">
because if test is truthy you'll already get the required
attribute, and if test is falsy you won't get the attribute. The true : false
part is redundant, much like this...
if (condition) {
return true;
} else {
return false;
}
// or this...
return condition ? true : false;
// can *always* be replaced by...
return (condition); // parentheses generally not needed
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">
In html use
<input :required="condition" />
And define in data property like
data () {
return {
condition: false
}
}