ChatGPT解决这个技术问题 Extra ChatGPT

VueJS 有条件地为元素添加属性

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

有任何想法吗?

虽然不是那么明显(因此造成混淆),但文档实际上确实说如果属性值评估为 false 则属性被省略(vuejs.org/v2/guide/syntax.html#Attributes
实际上,文档说如果 “...具有 nullundefinedfalse”的值,则不会添加属性,这与评估为 false 的 JS 脚本不同.这意味着空字符串在 JavaScript 中是虚假的,但仍会将属性添加到 DOM。为防止这种情况发生,您可以尝试 v-bind:name="name || false"
@AlexanderB如果这是真的,我如何通过道具将显式 false 传递给子组件?
@BruceSun,如果上下文中的属性在您给它错误值时“无意”消失 - 尝试将其作为字符串 'false' 传递。在其他情况下,当您需要控制元素上是否存在非布尔 html 属性时,您可以按照此处的建议使用带有 v-if 的条件呈现:github.com/vuejs/vue/issues/7552#issuecomment-361395234
@AlexanderB 我想我必须纠正自己 - 我应该说 attribute 而不是 prop。我们可以通过组件属性而不是属性(不被识别为属性)安全地传递显式 false。我对么?

c
cymruu

尝试:

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

更新:在 Vue 3 中已更改,请参阅此答案 https://stackoverflow.com/a/64598898


长格式是 <input v-bind:required="test ? true : false">
任何语言的 anythingAtAll : ? true : false(或 if (condition) { return true; } else { return false; })都是...不合时宜。只需使用 return (condition),或者在这种情况下,使用 <input :required="test">
如果您确定变量 testboolean,您可以使用 :required="test"
使用其中 required 是布尔组件属性的 :required="required" 会导致 <el required="required">为了我
请注意,这在 Vue 3 中发生了变化,请参阅下面的答案之一
S
Syed

最简单的形式:

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

请注意,这取决于组件!如果您的属性接受 String 值,那么通过将其设置为 false,您可能会收到 type check 错误。所以将它设置为 undefined 而不是 false。 docs
@Syed 你的答案使用双感叹号!!我在昨天之前从未见过这种语法,在代码审查期间我遇到了这个:--<input :required="!!!recipe.checked" v-model="recipe.pieType"><select :required="!!!recipe.checked" v-model="recipe.ingredients" :options="ingredients"></select>你知道 !!! (3) 对 {4 的含义吗? } 价值?谢谢。
@Chris22 !test 和 !!!test 之间没有区别,因为 !!!test 只是 !!(!test) 并且因为 !test 是一个布尔值, !!(!test) 只是它的双重否定,因此相同的。检查:stackoverflow.com/a/25318045/1292050
@Syed 谢谢。按照您的链接,I found this one as well and I agree。 :^)
@Syed 所说的并非不真实
J
Jouni Kantola

Vue 3 中更改了属性的条件渲染。要省略属性,请使用 nullundefined

视图 2:

<div :attr="false">
Result: <div>

<div :attr="null">
Result: <div>

视图 3:

<div :attr="false">
Result: <div attr="false">

<div :attr="null">
Result: <div>

谢谢,这是我一直在寻找的答案。
undefined 适用于我正在使用的少数 Vue 包
正确,完整和简洁的答案,谢谢。
S
Stephen P

<input :required="condition">

您不需要 <input :required="test ? true : false">,因为如果 testtruthy 您将已经获得 required 属性,如果 test 是 < em>falsy 你不会得到这个属性。 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">


S
Satyam Pathak

您可以通过强制传递 boolean,将 !! 放在变量之前。

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

但是我想提请您注意以下情况,其中接收组件已为 props 定义了 type。在这种情况下,如果 isRequired 已将类型定义为 string,则通过 boolean 使其类型检查失败,您将收到 Vue 警告。要解决此问题,您可能希望避免传递该道具,因此只需将 undefined 回退,该道具将不会发送到 component

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

解释

我遇到了同样的问题,并尝试了上述解决方案!是的,我没有看到 prop,但这实际上并不能满足此处的要求。

我的问题 -

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

在上述情况下,我期望没有将 my-prop 传递给子组件 - <any-conponent/> 我在 DOM 中看不到 prop 但在我的 <any-component/> 组件中,会弹出一个错误道具类型检查失败。与子组件一样,我希望 my-propString,但它是 boolean

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

这意味着子组件确实收到了该道具,即使它是 false。这里的调整是让子组件接受 default-value 并跳过检查。通过 undefined 可以工作!

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

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


这就是在使用选择选项(和选择的属性)时对我有用的方法
n
nikk wong

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

<input v-bind="attrs" />

其中 attrs 被声明为对象:

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

这将导致:

<input required type="text"/>

非常适合具有多个属性的情况。


Z
Zaheer Alvi

您可以在属性前添加冒号(也可以使用条件),例如

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

如果你想设置像 props 这样的动态值,那么你也可以在属性名称之前使用冒号,例如:

<Child :data="userList" />

N
Nipun Jain

在 html 中使用

<input :required="condition" />

并在数据属性中定义,如

data () {
   return {
      condition: false
   }
}

G
Guilherme Nunes

您也可以使用计算

<input :required="isRequired" />

计算:

computed: {
   isRequired () {
      return someLogic //Boolean, true or false
   }

V
VMK053

你可以这样写:

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