VueJS conditionally add an attribute for an elemen

2019-01-17 02:51发布

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?

3条回答
SAY GOODBYE
2楼-- · 2019-01-17 02:53

<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">

查看更多
Lonely孤独者°
3楼-- · 2019-01-17 03:08

Simplest form:

<input :required="test">   // if true
<input :required="!test">  // if false
<input :required="!!test"> // test ? true : false
查看更多
仙女界的扛把子
4楼-- · 2019-01-17 03:12

Try:

<input :required="test ? true : false">
查看更多
登录 后发表回答