[Vuejs]-Mcqs to highlight wrong and correct answer using vue.js and vuetify

0👍

Working codepen here: https://codepen.io/CodingDeer/pen/rXmNdO

  1. I restructured your data slightly to be able to make vue loop through the options. This is not necessary but I think better than having to hard code the options.
items: [
      {
        t: 'Title',
        options: {
          a: 'Opt 1',
          b: 'Opt 2',
          c: 'Opt 3',
          d: 'Opt 4'
        },
        ans: 'c'
      },
    ]
  1. Add dynamic classes to color the background of the options depending on whether it was the correct answer. Here I also disable the list items if the correct answer is chosen. It’s an easy way to prevent people from clicking again.
      <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. The javascript! Keep a list of clicked options by the user. Whenever a user clicks an option, if it doesn’t already exist in the list, add it to the list. If the option is the answer, clear the list and then add the answer option into the list. Note that you need to put each question group into a component for this to work.
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);
        }
      }
    }
  }
})

Leave a comment