javascriptvuejs3togglevue-propsv-model

Toggle Button With Props & emit


this is my first time using props and I can't figure out what's the problem

I want to make a component of the toggle button and then use it anywhere with an entry data, but it doesn't work as I expect could you please help me to fix this? here is my component:

<template>
  <div>
    <label v-for="(label, option) in options" :key="option">
      <input
        type="radio"
        :value="option"
        :checked="option = value"
        @change="$emit('input', option)"
      />
      <slot :name="option">
      {{ label }}
    </slot>
    </label>
  </div>
</template>
<script>
export default {
  name: 'ToggleSwitch',
  props: {
    value: {
      type: String,
      required: true
    },
    options: {
      type: Object,
      required: true
    }
  }
}
</script>

and here is where I want to use this button :

  <toggle-switch v-model="value" :options="options">
  <template #Single>
  <p>test slot</p>
  </template>
  <template #Subscription>
  <p>test slot2</p>
  </template>
  </toggle-switch>
<script>
import ToggleSwitch from '../components/ToggleSwitch.vue'
export default {
  components: {
    ToggleSwitch,
  },
  data() {
    return {
      value: 'Single',
      users: useUsersListStore(),
    }
  },
  computed: {
    options() {
      return {
        Single: 'ggg',
        Subscription: 'bbb',
      }
    }
  },
</script>

Solution

  • a same radio name is required when you want toggle item, and :checked="option == value" not :checked="option = value"

      <template>
          <div>
            <label v-for="(label, option) in options" :key="option">
              <input
                type="radio" :name="name"
                :value="option"
                :checked="option == value"
                @change="$emit('input', option)"
              />
              <slot :name="option">
              {{ label }}
            </slot>
            </label>
          </div>
        </template>
        <script>
        export default {
          name: 'ToggleSwitch',
          props: {
            value: {
              type: String,
              required: true
            },
            name: {
              type: String,
              required: true
            },
            options: {
              type: Object,
              required: true
            }
          }
        }
        </script>
    //to use 
    <toggle-switch v-model="value" name="testname" :options="options">