'How to reset v-model

i have toggle and reset button:

<template>
  <label :for='id + "_button"' :class='{"active": isActive}' class='toggle__button'>
   <input type='checkbox' :id='id + "_button"' v-model='checkedValue'>
   <span class='toggle__switch'></span>
   <button @click='reset()'>reset</button>
  </label>
</template>

script:

export default ({
 props: {
  defaultState: {
    type: Boolean,
    default: false
  },
  id: {
    type: String,
    default: 'primary'
  }
 },
 data() {
  return {
    currentState: this.defaultState
  };
 },
 computed: {
   isActive() {
    return this.currentState;
  },
 checkedValue: {
  get() {
    return this.defaultState;
  },
  set(newValue) {
    this.currentState = newValue;
    this.$emit('change', newValue);
   }
 }
},

 methods: {
  reset() {
    this.checkedValue = false ;
  }
 }
});

toggle works well. But when you press the reset button, a bug appears. At which, toggle works only from the 2nd time. What needs to be added/fixed?



Solution 1:[1]

Your component is a custom component which could interact with parent one using two-way binding by defining a value as prop and emit the new value when the checkbox changes state :


<template>
  <label :for='id + "_button"' :class='{"active": isActive}' class='toggle__button'>
   <input type='checkbox' :id='id + "_button"' :value='value' @change="emitVal($event)">
   <span class='toggle__switch'></span>
   <button @click='emitVal(false)'>reset</button>
  </label>
</template>


script :

export default ({
 props: {
  value: {
    type: Boolean,
    default: false
  },
  id: {
    type: String,
    default: 'primary'
  }
 },

 methods: {
  emitVal(val) {
    this.$emit('input',val)
  }
 }
});

in parent :

<customCheckbox id="secondary" v-model="someValue"/>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Boussadjra Brahim