代码之家  ›  专栏  ›  技术社区  ›  devAR

单击其他组件时,单选按钮未保持选中状态

  •  0
  • devAR  · 技术社区  · 2 年前

    我有这个父组件

    问题

    <template>
      <div class="question-container">
        <div class="question">
          <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>
    

    这个子组件名为

    选择

    <template>
      <div class="choice">
        <div v-for="(choice, index) in choices" v-bind:key="index">
          <label>
            <input type="radio" name="answer" />
            <span class="label-text">{{ choice }}</span>
          </label>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      name: "Choice",
      props: {
        choices: Array,
      },
    };
    </script>
    

    问题是,当您在一个组件上选择单选按钮时,然后转到另一个组件并尝试在该组件上选择单选按钮时。单选按钮将从其他组件中取消选中。倍数 问题 渲染组件,每个组件都有单选按钮。当您单击 问题 组件,则从其他组件中取消选择所有选定的单选按钮。希望我有道理。我该如何解决这个问题?

    1 回复  |  直到 2 年前
        1
  •  2
  •   Djave    2 年前

    使用 name= 单选按钮上的属性是HTML用于将其与其他收音机分组以获得相同输入的属性。您需要每个问题都具有唯一性。

    这些问题已经有了 number prop(我希望它是某种ID?如果不是,可以为每个属性添加一个ID属性)

    我会将此传递给选择:

    <Choice :choices="question.choices" :id="number"/> 
    

    然后在选项中渲染:

    <template>
      <div class="choice">
        <div v-for="(choice, index) in choices" v-bind:key="index">
          <label>
            <input type="radio" :name="`answer-${id}`" />
            <span class="label-text">{{ choice }}</span>
          </label>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      name: "Choice",
      props: {
        choices: Array,
        id: Number
      },
    };
    </script>
    

    这将渲染

    <input type="radio" name="answer-1" />