[Vuejs]-How do I bind a class if the input type attribute is checkbox? + Vuejs

0👍

I guess type is a prop?
I would move the logic to a computed property and check if type is checkbox:

computed: {
  checkboxClass: function () {
    return this.type === 'checkbox' ? 'o-pf-input--cbx' : ''
  }
}

Which is then used:

<input :type="type" class="o-pf-input" :class="checkboxClass" :placeholder="placeholder" :name="placeholder" :value = 'value' @input="value = $event.target.value">

You can read more about computed properties here: https://v2.vuejs.org/v2/guide/computed.html

If type isn’t known you might have to get a reference to the actual element and check the type manually. See here for a reference on ref: https://v2.vuejs.org/v2/api/#ref

0👍

First, try getting rid of the double class specification. Put your static classes as literals in the bound class, ie :class="['type',!isCheckbox...]". If this gets complicated, remove it to a specific function in your methods.

Next, instead of an isCheckbox property, why don’t you test the type variable, so there’s one source of truth.

Next, if you want to pass different inputs to different instances of the same component, you will want to use props, not data. Data will be the same for all instances.

Lastly, are you sure you want put checkboxes and other inputs together in one component? What do they have in common? This looks a bit like cutting a pizza into rectangles.

Leave a comment