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

什么好主意吗?


当前回答

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

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

其他回答

值得注意的是,如果你想有条件地添加属性,你也可以添加一个动态声明:

<input v-bind="attrs" />

其中attrs被声明为一个对象:

data() {
    return {
        attrs: {
            required: true,
            type: "text"
        }
    }
}

这将导致:

<input required type="text"/>

适用于具有多个属性的情况。

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

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

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

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 type="text" name="username" :required="condition ? true : false">

你可以在属性前添加冒号(也可以使用条件)

<div :class="current? 'active': '' " > 
<button :disabled="InvalidForm? true : false " >

如果你想设置一个动态值,比如props,那么你也可以在属性名前使用冒号,比如:

<Child :data="userList" />