在VueJS中,我们可以使用v-if添加或删除DOM元素:

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

但是是否有一种方法可以添加/删除dom元素的属性,例如下面的条件设置所需的属性:

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

通过类似于:

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

什么好主意吗?


当前回答

Try:

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

更新:Vue 3已经改变了,请参阅这个答案https://stackoverflow.com/a/64598898

其他回答

你可以通过强制传递布尔值,输入!!在变量之前。

let isRequired = '' || null || undefined
<input :required="!!isRequired"> // it will coerce value to respective boolean 

但我想让您注意下面的情况,其中接收组件已经为道具定义了类型。在这种情况下,如果isRequired已经定义了类型为字符串,那么传递布尔使它类型检查失败,你将得到Vue警告。为了解决这个问题,你可能想要避免传递那个道具,所以只要输入undefined fallback,道具就不会被发送到组件

let isValue = false
<any-component
  :my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>

解释

我也经历过同样的问题,并尝试了以上的解决方案!! 是的,我没有看到道具,但这实际上不满足这里的要求。

我的问题是

let isValid = false
<any-component
  :my-prop="isValue ? 'Hey I am when the value exist': false"
/>

在上面的情况下,我所期望的是没有my-prop被传递给子组件- <any-component/>我没有看到DOM中的道具,但在我的<any-component/>组件中,一个错误弹出prop类型检查失败。在子组件中,我期望my-prop是一个字符串,但它是布尔值。

myProp : {
 type: String,
 required: false,
 default: ''
}

这意味着子组件确实收到了道具,即使它是假的。这里的调整是让子组件接受默认值并跳过检查。虽然通过了未定义的作品!

<any-component
  :my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>
 

这是有效的,我的子道具有默认值。

<输入:要求= "条件" >

你不需要<input:required="test ?因为如果test为真,你就已经得到了所需的属性,如果test为假,你就不会得到属性。真假部分是多余的,就像这样……

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使用!!很管用。 <所需输入:= " ! !条件”>

在html使用中

<input :required="condition" />

并在data属性中定义

data () {
   return {
      condition: false
   }
}

最简单的形式:

<input :required="test">   // if true
<input :required="!test">  // if false
<input :required="!!test"> // test ? true : false

你可以这样写:

<input type="text" name="username" :required="condition ? true : false">