Toggle Button With Props & emit

74 views Asked by At

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>
2

There are 2 answers

0
Siimo On

You are emiting events from child components using "emit", but your parent component isn't listening to those events.

First option is to add listener where the component is used. https://vuejs.org/guide/components/events.html#emitting-and-listening-to-events

Second option is to use two-way data binding between parent and child component. https://vuejs.org/guide/components/v-model.html

4
moon On

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">