Using Vuejs to dynamically apply a class and trigger a function based on a specified condition

I am currently facing three small issues in my Vue app. The first problem involves class binding. I have a bootstrap card that displays a question and its related answers. When a user clicks on a radio input, their answer is saved and the other options are disabled.

I am dynamically checking if the user's answer is correct, but I am struggling to change the class of the card border accordingly. I want the border to be black before the answer is revealed, and then change to border-success if the answer is correct, or border-danger if it is wrong. However, my attempts with the code provided have not been successful as the border is always given the border-danger class even if no answer has been chosen.

<div class="card text-dark bg-light border-secondary shadow mt-3 mb-3" :class="[userAnswers[qindex] === correctAnswers[qindex] && answered[qindex] ? 'border-success' : 'border-danger']">

Another issue I encountered is with the card footer in the app's UI. I added a card footer that is initially hidden until the question is answered. It is supposed to display the correct answer, but I noticed a graphical glitch where it briefly appears and then disappears when a correct answer is given.

<div class="card-footer bg-transparent border-success fw-bold" v-show="userAnswers[qindex] !== correctAnswers[qindex]">The correct answer is: {{ correctAnswers[qindex] }}</div>

In an attempt to fix this, I have experimented with both v-if and the current v-show methods, as well as adding a CSS transition to the element, but none seem to resolve the issue.

.card-footer {
  transition: ease-in .3s;
}

The final and most critical problem involves a conditional check. I want to display a modal when the user has answered all available questions. I have tried adding an if() statement in the mounted hook of Vue, but it never triggers. I have also attempted to call the method inside the .then() callback of the axios call that checks each question's answer, but again without success.

export default {
  name: 'App',
  data(){
    return {
      isLoading: true,
      showResult: false,
      elaspedTime: null,
      questions: [],
      answered: {},
      userAnswers: [],
      correctAnswers: []
    }
  },
  mounted(){
    this.init();
    // This statement will never be evaluated 
    if( this.answered.length === this.questions.length ){
      this.quizResults();
    }
  },
  methods: {
    init(){
      axios({
        method: 'GET',
        url: 'http://localhost:8990/init'
      }).then( (res) => {
        this.questions = [];
        this.questions = res.data;
        console.log(this.questions);
        this.isLoading = false;
      });
    },
    checkAnswer(qindex, index, value){
      // console.log(qindex, index, value);
      this.answered[qindex] = true;
      this.userAnswers.push(value);
      axios({
        method: 'POST',
        url: 'http://localhost:8990/answercheck',
        data: {
          questionIndex: index,
          choice: value
        }
      }).then( (res) => {
        console.log(res.data);
        this.correctAnswers.push(res.data.correctAnswer);
        
      });
    },
    quizResults(){
      // Implement further logic after all questions are answered
      console.log('Results');
    }
  }
}

If anyone can provide assistance in resolving these issues, I would greatly appreciate it. Thank you.

Answer №1

There are three questions that need addressing.

Concerning the first query:

The issue lies in the wrapping of the condition within [] for the class. This adjustment should rectify it:

<div class="card text-dark bg-light border-secondary shadow mt-3 mb-3" :class="!userAnswers[qindex] ? ‘’ : userAnswers[qindex] === correctAnswers[qindex] && answered[qindex] ? 'border-success' : 'border-danger'">

Regarding the second question:

There may be a scenario where while waiting for a response from the server, userAnswers[qindex] holds the correct answer value, but correctAnswers[qindex] remains undefined until the response is received. In that split second, they may not be equal, causing the footer to briefly appear and then disappear. To address this, validate:

correctAnswers[qundex] && userAnswers[qindex] !== correctAnswers[qindex]

With respect to the third inquiry

The recommended approach would be to place the condition within the .then block of checkAnswer() as you had attempted. The issue arises from checking this.answered.length, where this.answered is an Object, not an Array, and lacks a .length property. Verify it by:

Object.keys(this.answered).length === this.questions.length

Therefore, the revised method should be:

checkAnswer(qindex, index, value){
      // console.log(qindex, index, value);
      this.answered[qindex] = true;
      this.userAnswers.push(value);
      axios({
        method: 'POST',
        url: 'http://localhost:8990/answercheck',
        data: {
          questionIndex: index,
          choice: value
        }
      }).then((res) => {
        console.log(res.data);
        this.correctAnswers.push(res.data.correctAnswer);
        if(Object.keys(this.answered).length === this.questions.length){
              this.quizResults();
        }
      });
    },

On another note, the reason the condition failed when called within mounted() is because mounted only triggers upon component initialization – it does not monitor changes. Further information can be found in the Vue documentation

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing a computed property within a method in Vue.js - a step-by-step guide

Currently, I am facing an issue with accessing the "generatedOrder" object from a method named "onSubmit()". This object was initially stored in another component and is retrieved using a computed property in the component where it is required. While I can ...

What is the best way to align the navbar elements horizontally and at an equal height?

I am currently working on creating a navigation bar for my webpage using bootstrap. I have utilized the <li> tags, but I am facing an issue where the items are not lining up properly. Below is the code for reference: <nav class="navbar navbar ...

When using ESLint together with React, you may encounter errors related to `no-unused-vars

I've configured eslint and eslint-plugin-react. After running ESLint, I'm encountering no-unused-vars errors for all React components. It seems that the linter is not recognizing JSX or React syntax. Any solutions? For example: app.js import ...

Make the background image within a button stretch to completely cover the button

I need assistance with creating a button that has a large image as its background. The challenge I'm facing is that the image fits vertically within the button, but horizontally it repeats unless I use 'no-repeat', which leaves empty space i ...

The functionality of jQuery's appendTo method seems to be malfunctioning

I am trying to display an image with a popup using jQuery mobile. In my loop, I have the code below: for( var i = 0; i < imageArray.length; i++ ) { counter ++; // Create a new Image element var img = $('<img data-rel="popup" class=" ...

Could you explain the significance of the code "a[href*=#]:not([href=#])"?

I'm a bit confused about the meaning of this code. Can someone explain it to me? a[href*=#]:not([href=#]) Appreciate the help! ...

What is the best way to add JSON data to a table?

I have developed a php script to create json data. However, I am facing an issue while trying to display this generated json data in a table. While my php code successfully generates the data, it is unable to insert it into the table. I would appreciate an ...

problem with selection of date and month in dropdown list with jquery

Recently, I've been dabbling in jQuery and decided to create two list boxes using it. One box contains dates while the other contains months. It's quite handy since I need them in different sections of my HTML page. However, when attempting to en ...

Eliminate php file extensions using .htaccess

Currently, I am developing a script and looking to change the links in the following way: www.mysite.com/sign-up.php to www.mysite.com/sign-up and www.mysite.com/profile.php?username=abc to www.mysite.com/profile/abc I have come across this code that ...

Preventing the need to reset JavaScript text inputs

I'm encountering a strange issue in my code. I'm developing a graphing calculator that requires users to enter multiple expressions for evaluation. I have a text input and a button that adds a new input to the parent div whenever it is clicked: d ...

Converting a decimal Unicode to a string in Javascript/Node: a beginner's guide

In my database, I have Arabic sentences that contain decimal unicodes for quotation marks and other elements. For example, here is a sample text: "كريم نجار: تداعيات &#8220;كورونا&#8221; ستغير مستقبل سوق السي ...

Issue with Nivo Lightbox: image not properly centered or resizing correctly

Whenever an image is clicked, it opens in the Nivo lightbox. This feature used to work flawlessly, but recently, it seems to be experiencing issues. The image should be centered and resize responsively to stay in the center. (For example, it worked correct ...

Deferred computed property fails to recognize the final character entered into the input field

I am facing an issue with my automated tests using selenium. The problem lies with a particular input field in a web form: <input data-bind="value: searchText, valueUpdate: 'afterkeydown'"></input> Here is the model associated with ...

Using axiosjs to send FormData from a Node.js environment

I am facing an issue with making the post request correctly using Flightaware's API, which requires form data. Since Node does not support form data, I decided to import form-data from this link. Here is how my code looks like with axios. import { Fl ...

Is it possible to center without specifying a fixed width?

Check out this demo link Is there a way to center all the divs and paragraphs under the main div without specifying a fixed width value? I want to remove the 300px width in the .center class and have all the elements align center. Specifically, how can I ...

JavaScript Lint Warning: Avoid declaring functions inside a loop - unfortunately, there is no way to bypass this issue

In my React JS code snippet, I am attempting to search for a value within an object called 'categories' and then add the corresponding key-value pair into a new map named sortedCategories. var categoriesToSort = []; //categoriesToSort contains ...

Attempting to insert the symbol "$gt" into a query for a search. {[CastError: Unable to convert value "[object Object]" to date at path "createdAt"]}

In the following code snippet: Reviews.find({createdAt : {"$lt" : app.locals.lastDate}}), I am trying to dynamically change the $lt to $gt. app.post("/scroll", function(req, res){ console.log("req.body...", req.body); var sortCreate = req.body.old ...

Implementing Facebook conversion tracking when there is no distinct 'Thank you' page can be done by utilizing the onclick event

Currently working on incorporating Facebook conversion tracking into a Facebook Tab. To see the page, visit this link. The issue I'm facing is that a separate page does not load after the form has been submitted. Is there a way to execute a section of ...

Leveraging Next.js to efficiently handle multiple asynchronous requests with NextResponse

I have developed a login/signup application using NextJS. When attempting to log in, the logic in my route.ts file sends requests to a MongoDB database to check if the user exists and if the password is correct. However, instead of receiving the expected 4 ...

Collaboratively accessing a shared constant in two separate JavaScript files

I am diving into the world of JavaScript and Node.js. I am currently experimenting with Puppeteer to extract the text value of a tag and store it in a constant variable. However, I am encountering difficulties when trying to integrate this value into my ...