You need to enable JavaScript to run this app. Vue.js中v-for生成的元素如何根据点击状态绑定不同Bootstrap类
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中v-for生成的元素如何根据点击状态绑定不同Bootstrap类

实现方案

第一步:调整数据存储逻辑

原answeredQuestions仅存储了问题是否回答的状态,需要调整为存储每个问题的选中选项下标,满足后续类匹配的需求:

export default {
  name: 'Survey',
  data() {
    return {
      n: 0,
      // 数组下标对应问题索引,值为该问题选中的选项下标,未回答则为undefined
      answeredQuestions: [],
    }
  },
  computed: {
    questions() {
      return this.$store.getters.survey;
    },
  },
  methods: {
    showNext() {
      if( this.n < this.questions.length ){
        this.n++
      }
    },
    isAnswered(index) {
      return this.n !== index ? 'hide' : '';
    },
    checkAnswer(questionIndex, choiceIndex) {
      // 存储当前问题的选中选项
      this.answeredQuestions[questionIndex] = choiceIndex
      this.showNext();
      // 保留你原有校验逻辑
    }
  }
}

第二步:修改模板添加动态类绑定

使用Vue的对象语法类绑定,直接在模板内完成状态判断,无需额外新增计算属性:

<ul class="list-group list-group-flush">
   <li 
    class="list-group-item list-group-item-action" 
    v-for="(choice, index) in item.choices" 
    :key="index"
    :class="{
      // 问题已回答时所有选项加disabled类
      disabled: answeredQuestions[item.questionIndex] !== undefined,
      // 仅选中的选项加active类
      active: answeredQuestions[item.questionIndex] === index
    }"
   >
     <small 
      class="" 
      @click.prevent="answeredQuestions[item.questionIndex] === undefined && checkAnswer(item.questionIndex, index)"
     >
      {{ index }}) {{ choice }}
     </small>
   </li>
 </ul>

方案说明

  • 逻辑轻量,所有绑定逻辑直接在模板内完成,不需要额外维护冗余状态
  • 点击事件加了前置判断,已回答的问题不会重复触发校验逻辑,避免异常提交
  • 完全匹配Bootstrap 5列表组的样式规范,交互效果和原生Bootstrap行为一致

内容的提问来源于stack exchange,提问作者newbiedev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 13:45:03