<style lang="scss" scoped>
</style>
<template>
  <div>
    <q-checkbox
      v-for="item in checkboxList"
      :key="item.label"
      v-model="checkedValue"
      :val="item.value"
      @input="changeValue(item)"
      >{{ item.label }}</q-checkbox
    >
  </div>
</template>
<script>
export default {
  props: {
    checkboxList: {
      type: Array,
      default: () => [],
    },
    radio: {
      type: Boolean,
      default: true,
    },
    value: {
      default: "",
    },
  },
  data() {
    return {
      checkedValue: [],
    };
  },
  mounted() {
    this.prevVal = JSON.parse(JSON.stringify(this.checkedValue));
  },
  watch: {
    value: function () {
      if (this.value) {
        this.checkedValue = [this.value];
      }
    },
  },
  methods: {
    changeValue(item) {
      const index = this.prevVal.findIndex((el) => item.value === el);
      if (this.radio) {
        if (index > -1) {
          this.checkedValue = [];
        } else {
          this.checkedValue = [item.value];
        }
      }
      this.$emit(
        "input",
        this.radio ? this.checkedValue[0] : this.checkedValue
      );
      this.prevVal = JSON.parse(JSON.stringify(this.checkedValue));
    },
  },
};
</script>