VueJS conditionally adds an attribute for an element
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 the dom element, for example, for the following conditionally set the required attribute:
Username: <input type="text" name="username" required>
something similar to:
Username: <input type="text" name="username" v-if="name.required" required>
Any ideas?
<input :required="condition">
<input :required="test ? true : false">
, test , required
, test , . true : false
, ...
if (condition) {
return true;
} else {
return false;
}
// or this...
return condition ? true : false;
// can *always* be replaced by...
return (condition); // parentheses generally not needed
<input :required="condition">
( ) , - ; Syed !!
.
<input :required="!!condition">
, ! , prop
, .
-
let isValid = false
<any-component
:my-prop="isValue ? 'Hey I am when the value exist': false"
/>
, my-prop
- <any-conponent/>
prop
DOM
<any-component/>
. , , my-prop
String
boolean
.
myProp : {
type: String,
required: false,
default: ''
}
This means that the child component has received support, even if it is false
. Here you can configure the child component to default-value
by default-value
and also skip the check. Missed undefined
work though!
<any-component
:my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>
This works, and my child prop is the default.