VueJS conditionally add an attribute for an element

前端 未结 7 1517
旧时难觅i
旧时难觅i 2020-12-02 09:15

In VueJS we can add or remove a DOM element using v-if:


but is there a wa

相关标签:
7条回答
  • 2020-12-02 09:25

    It's notable to understand that if you'd like to conditionally add attributes you can also add a dynamic declaration:

    <input v-bind="attrs" />
    

    where attrs is declared as an object:

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

    Which will result in:

    <input required type="text"/>
    

    Ideal in cases with multiple attributes.

    0 讨论(0)
  • 2020-12-02 09:29

    Conditional rendering of attributes changed in Vue 3. To omit an attribute use null or undefined.

    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>
    
    0 讨论(0)
  • 2020-12-02 09:32

    Try:

    <input :required="test ? true : false">
    
    0 讨论(0)
  • 2020-12-02 09:34

    Simplest form:

    <input :required="test">   // if true
    <input :required="!test">  // if false
    <input :required="!!test"> // test ? true : false
    
    0 讨论(0)
  • 2020-12-02 09:42

    <input :required="condition">

    You don't need <input :required="test ? true : false"> because if test is truthy you'll already get the required attribute, and if test is falsy you won't get the attribute. The true : false part is redundant, much like this...

    if (condition) {
        return true;
    } else {
        return false;
    }
    // or this...
    return condition ? true : false;
    // can *always* be replaced by...
    return (condition); // parentheses generally not needed
    

    The simplest way of doing this binding, then, is <input :required="condition">

    Only if the test (or condition) can be misinterpreted would you need to do something else; in that case Syed's use of !! does the trick.
      <input :required="!!condition">

    0 讨论(0)
  • 2020-12-02 09:43

    In html use

    <input :required="condition" />
    

    And define in data property like

    data () {
       return {
          condition: false
       }
    }
    
    0 讨论(0)
提交回复
热议问题