【问题标题】:Mcqs to highlight wrong and correct answer using vue.js and vuetifyMcqs 使用 vue.js 和 vuetify 突出显示错误和正确的答案
【发布时间】:2019-12-07 05:32:53
【问题描述】:

如何一一突出显示选项以显示错误或正确选项。例如如果用户选择了错误的选项,它应该变为红色,直到用户选择正确的选项,将其颜色变为绿色。如图所示,我无法创建组件:

question: {
    t: "Question title"
    a: "Option 1"
    b: "Option 2"
    c: "Option 3"
    d: "Option 4"
    ans: "b"
}

【问题讨论】:

  • 您如何跟踪已选择的项目?我想您将其存储在某个变量中?
  • 您可以将用户选择的选项推送到一个数组中,并使用一些逻辑将问题与数组进行比较以确定突出显示颜色。如果您可以在尝试生成此组件时提供 codepen 或 jsfiddle,我们将很乐意帮助您进行故障排除。
  • @Cathy Ha 这里是代码笔链接:codepen.io/mubeenmazhar/pen/pMRBZW

标签: javascript vue.js vue-component vuetify.js


【解决方案1】:

在这里工作的代码笔:https://codepen.io/CodingDeer/pen/rXmNdO

  1. 我稍微重组了您的数据,以便能够使 vue 循环通过选项。这不是必需的,但我认为比硬编码选项更好。
items: [
      {
        t: 'Title',
        options: {
          a: 'Opt 1',
          b: 'Opt 2',
          c: 'Opt 3',
          d: 'Opt 4'
        },
        ans: 'c'
      },
    ]
  1. 添加动态类以根据是否为正确答案为选项的背景着色。如果选择了正确的答案,我也会在此处禁用列表项。这是防止人们再次点击的简单方法。
      <v-list>
        <v-list-item-group>
          <v-list-item 
            v-for="(option, key) in item.options"
            :class="{'incorrect': userInput.indexOf(key) != -1 && key != item.ans, 
                     'correct': userInput.indexOf(key) != -1 && key == item.ans}"
            :disabled="userInput.indexOf(item.ans) != -1"
            @click="addOption(key, item.ans)">
            <v-list-item-content>
              <v-list-item-title v-text="option">
              </v-list-item-title>
            </v-list-item-content>
          </v-list-item>
        </v-list-item-group>
      </v-list>
  1. JavaScript!保留用户单击的选项列表。每当用户单击选项时,如果列表中尚不存在该选项,则将其添加到列表中。如果选项是答案,请清除列表,然后将答案选项添加到列表中。请注意,您需要将每个问题组放入一个组件中才能正常工作。
new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    items: [
      {
        t: 'Title',
        options: {
          a: 'Opt 1',
          b: 'Opt 2',
          c: 'Opt 3',
          d: 'Opt 4'
        },
        ans: 'c'
      },
    ],
    userInput: [],
  }),
  methods: {
    addOption(selected, ans) {
      if (selected == ans) {
        this.userInput.length = 0;
        this.userInput.push(selected);
      } else {
        const index = this.userInput.indexOf(selected);
        if (index == -1) {
          this.userInput.push(selected);
        }
      }
    }
  }
})

【讨论】:

    猜你喜欢
    • 2014-06-02
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多