在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>
什么好主意吗?
你可以通过强制传递布尔值,输入!!在变量之前。
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"
/>
这是有效的,我的子道具有默认值。