【问题标题】:VueJS conditionally add an attribute for an elementVueJS 有条件地为元素添加属性
【发布时间】:2017-08-10 00:03:29
【问题描述】:

在 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,则不会添加该属性,即不同于评估为假的 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。我说的对吗?

标签: javascript vue.js vuejs2


【解决方案1】:

试试:

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

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

【讨论】:

  • 长格式为&lt;input v-bind:required="test ? true : false"&gt;
  • anythingAtAll : ? true : false(或if (condition) { return true; } else { return false; })在任何语言中都是...... 不合时宜。只需使用return (condition),或者在这种情况下使用&lt;input :required="test"&gt;
  • 如果你确定变量testboolean,你可以直接使用:required="test"
  • 请注意,这取决于组件!如果您的属性接受String 值,那么通过将其设置为false,您可能会收到type check 错误。所以将它设置为undefined 而不是false。 docs
  • 使用 :required="required" 其中required 是一个布尔组件属性会导致 对我来说
【解决方案2】:

最简单的形式:

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

【讨论】:

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

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

Vue 2:

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

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

Vue 3:

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

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

【讨论】:

  • 谢谢,这就是我要找的答案。
  • undefined 适用于我正在使用的少数 Vue 包
  • 正确、完整、简洁的回答,谢谢。
【解决方案4】:

&lt;input :required="condition"&gt;

你不需要&lt;input :required="test ? true : false"&gt;,因为如果testtruthy,你已经得到required属性,如果testfalsy 你不会得到这个属性。 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

那么,进行这种绑定的最简单方法是&lt;input :required="condition"&gt;

只有当测试(或条件)可能被误解时,你才需要做其他事情;在这种情况下,Syed 使用 !! 就可以了。
&lt;input :required="!!condition"&gt;

【讨论】:

    【解决方案5】:

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

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

    但我想提请您注意以下情况,其中接收组件为道具定义了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 传递给子组件-&lt;any-conponent/&gt; 我在DOM 中看不到prop,但在我的&lt;any-component/&gt; 组件中出现错误弹出道具类型检查失败。与子组件一样,我希望 my-prop 成为 String 但它是 boolean

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

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

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

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

    【讨论】:

    • 在使用选择选项(和选择的属性)时,这对我有用
    【解决方案6】:

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

    <input v-bind="attrs" />
    

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

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

    这将导致:

    <input required type="text"/>
    

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

    【讨论】:

      【解决方案7】:

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

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

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

      <Child :data="userList" />
      

      【讨论】:

        【解决方案8】:

        在html中使用

        <input :required="condition" />
        

        并在数据属性中定义,如

        data () {
           return {
              condition: false
           }
        }
        

        【讨论】:

          【解决方案9】:

          你也可以使用计算

          <input :required="isRequired" />
          

          计算:

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

          【讨论】:

            【解决方案10】:

            你可以这样写:

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

            【讨论】:

              猜你喜欢
              • 2012-10-09
              • 2015-04-05
              • 1970-01-01
              • 2017-04-28
              • 2019-08-19
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多