VueJS invert value in v-model

Viewed 2472

Here my code :

<input
   v-model="comb.inactive"
   type="checkbox"
   @click="setInactive(comb.id_base_product_combination)"
>

I need to apply the invert of the comb.inactive on the v-model.

Here what i tried :

<input
    v-model="comb.inactive == 1 ? 0 : 1"
    type="checkbox"
    @click="setInactive(comb.id_base_product_combination)"
>



<input
    v-model="comb.inactive == 1 ? false : true"
    type="checkbox"
    @click="setInactive(comb.id_base_product_combination)"
>

Do you have others ideas ?

3 Answers

Consider using true-value and false-value as shortcuts:

<input
    v-model="comb.inactive"
    type="checkbox"
    :true-value="false"
    :false-value="true"
>

Or in this case, where you may be looking for alternating integers, you can just set them directly.

<input
    v-model="comb.inactive"
    type="checkbox"
    :true-value="1"
    :false-value="0"
>

You should do the following:

<input
   v-model="comb.inactive"
   type="checkbox"
   @click="setInactive(comb.id_base_product_combination)"
>
mounted(){
      this.comb['inactive'] = !(this.comb['inactive']);
}

For better practice, you can use computed:

<input
   v-model="checkedItem"
   type="checkbox"
   @click="setInactive(comb.id_base_product_combination)"
>
computed: {
      checkedItem: {
        get: function () {
          return !this.comb['inactive'];
        },
        set: function (newVal) {
          console.log("set as you want")
        }
}

If you want to invert the v-model, then just make a custom input component!

checkbox-inverted

Vue.component('reverse-checkbox', {
  props: ['value', 'label'],
  template: `
    <label>
      <input
        type="checkbox"
        :checked="valueInverse"
        @input="onInputChanged"
      />
      <span>{{label}}</span>
    </label>
  `,
  computed: {
    valueInverse() {
      return !this.value;
    },
  },
  methods: {
    onInputChanged(e) {
      this.$emit('input', this.valueInverse);
    },
  },
});

Usage

Then you can use it with v-model like any other input component. more information about custom inputs here

<reverse-checkbox
  v-model="invertedModel"
  label="This checkbox will show the inverted value"
></reverse-checkbox>
Related