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
Answers
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
a same radio name is required when you want toggle item, and :checked="option == value" not :checked="option = value"