I have this parent component
Question
<template>
<div >
<div >
<h2>{{ number }}. {{ question.question }}</h2>
<Choice :choices="question.choices"/>
</div>
</div>
</template>
<script>
import Choice from "./Choice.vue";
export default {
name: "Question",
props: {
question: String,
number: Number,
},
components: {
Choice,
},
};
</script>
and this child component named
Choice
<template>
<div >
<div v-for="(choice, index) in choices" v-bind:key="index">
<label>
<input type="radio" name="answer" />
<span >{{ choice }}</span>
</label>
</div>
</div>
</template>
<script>
export default {
name: "Choice",
props: {
choices: Array,
},
};
</script>
The issue is that when you select a radio button on one component, then when you go to another component and try to select a radio button on the component. The radio button gets unselected from the other component. Multiple Question components are rendered and each of them has radio buttons. When you click a radio button on a Question component, all selected radio button gets unselected from the other components. Hope I made sense. How would I fix this?
CodePudding user response:
Using the name=
attribute on a radio button is what HTML uses to group it with other radios for the same input. You'll need this to be unique per question.
The questions already have a number
prop (which I hope is some sort of ID? If not, you could add an id attribute to each)
I would pass this to the choices:
<Choice :choices="question.choices" :id="number"/>
Then render it in the Choice:
<template>
<div >
<div v-for="(choice, index) in choices" v-bind:key="index">
<label>
<input type="radio" :name="`answer-${id}`" />
<span >{{ choice }}</span>
</label>
</div>
</div>
</template>
<script>
export default {
name: "Choice",
props: {
choices: Array,
id: Number
},
};
</script>
This renders
<input type="radio" name="answer-1" />