Unable to dynamically attach a class in Vue.js

I have exhausted all possible variations of this issue. I meticulously followed the official Vue guides, consulted numerous stack overflow posts, and went through various tutorials. I experimented with different syntaxes, quotations, array structures, and everything in between. Despite successfully toggling the data property, my CSS class fails to be applied to elements when 'isLearned' is true.

Below is the snippet of HTML code:

<li 
    v-for="(flashcard, index) in flashcards"
    v-bind:class="{learned: isLearned, flashcard}"
    @click="toggleSide(flashcard)">
    <p>{{flashcard.isFlipped ? flashcard.phrase : flashcard.definition}}</p>
    <button @click="learnedCard(flashcard, index)">Learned</button>
</li>

And here is the JavaScript code:

new Vue({
  el: "#esl-flashcards",
  data: {
    flashcards: flashcards,
    inputPhrase: '',
    inputDef: '',
    isLearned: false,
  },
  methods: {
    learnedCard: function(flashcard, index) {
      for (let i = 0; i < flashcards.length; i += 1){
        if (i === index) {
          flashcards[i].isLearned = !flashcards[i].isLearned;
        }
      };
    },
  },
});

Answer №1

There are a few issues that need to be addressed:

The property isLearned is actually a property of each individual flashcard object. So, when you are updating it like this:

flashcards[i].isLearned = !flashcards[i].isLearned;

You are correctly updating the property, but when checking for dynamic changes in the class using isLearned, you should reference it as flashcard.isLearned instead of just isLearned.

For example, change:

v-bind:class="{learned: isLearned, flashcard}"

To:

v-bind:class="{learned: flashcard.isLearned, flashcard}"

Additionally, when handling the card learning logic with a loop, make sure to refer to this.flashcards instead of just flashcards. However, since you are passing the index to the learnedCard() method, you can achieve the same result more efficiently by using the .find() method like this:

 learnedCard: function(flashcard, index) {
      var card = this.flashcards.find((f,i) => i===index)
      card.isLearned = !card.isLearned;
 },

See Working Demo below:

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

Enter the variable into the parameter

I'm working with some Javascript code: document.getElementById("Grid").style.gridTemplateRows = "repeat(3, 2fr)"; I'm trying to insert a variable as an argument to modify my CSS style. When I attempt the following: "repe ...

Is it possible to load a JS file using Node.js's `

Is there a way to load the contents of a js file into a variable without it returning as an object? How can I achieve this? server.js const file = require("./server/file.js"); ctx.body = `${file}`; // The expected output is "(function () { ...

Initial Search Function in a MEAN Stack Site

Working on a MEAN stack application for a school project, I'm almost done but struggling to add search functionality. Creating a search feature for ICD-10 codes in a medical app is my goal. Just need a basic search of symptoms or codes that displays ...

Retrieve data from a JSON gist by parsing it as a query string

I have a JavaScript-based application with three key files: index.html app.js input.json The app.js file references input.json multiple times to populate content in div elements within index.html. My goal is to enhance the functionality so that when acc ...

Personalizing Web Push Alerts (Google Chrome)

I successfully implemented a web push notification for Google Chrome using Google Project and Service Worker. One thing I'm curious about is how to customize or style the push notification. The plain message box doesn't quite cut it for me – I ...

$routeProvider - providing controller dependencies based on the URL path

Take a look at the following code snippet: var app = angular.module("app", [], function($routeProvider) { $routeProvider .when("/page1", { controller: "MyController" }) .when("/page2", { controller: "MyController" }) .when("/page3", { contro ...

Error location not displayed in Laravel/VueJS project console error message

Working on my laravel/Vuejs project, I encountered a challenging issue with VueJs troubleshooting. While developing a feature involving multiple vue components, everything seemed to be functioning as expected until I discovered an error message in the co ...

Discovering an Uncaught TypeError: Unable to access the property 'length' of an undefined value

Looking to implement a function that checks the status of the cart and displays output accordingly. The logic is as follows: If the cart is empty (cart.line_items.length returns false), then the EmptyCart function should be executed. The "line_items" var ...

"Is there a way to retrieve the props that have been passed down to a

I am looking to have custom props created in the root layer of my React app: import React from 'react' import App, { Container } from 'next/app' export default class MyApp extends App { static async getInitialProps({ Component, rout ...

What is the method for implementing two-way binding on a checkbox in Angular?

Within my accordion, I have a series of options in the form of checkboxes. Users are able to select these checkboxes, but I am seeking a way to pre-select certain checkboxes based on specific conditions. The challenge arises when these conditions are deter ...

Is there a way to display a date that is two days before the current date in a React date picker using only vanilla JavaScript

Greetings, I am currently immersed in working with a Shopify app that utilizes React. Unfortunately, I do not have access to their code base or API. The challenge at hand is sending the correct delivery date to the Shopify system. The app currently allows ...

Is Optional Chaining supported by Next.js on Vercel?

While Next.js does support Optional Chaining, I have encountered an issue when trying to deploy the following code snippet: module.exports = { experimental: { outputStandalone: true, }, images: { domains: process.env.NEXT_PUBLIC_IMAGE_DOMAINS ...

Express Module Paths Failing to Function Properly

When I first started building my routes, I had everything in one api.js file. However, I realized there might be a better approach, so I did some research online to see how others handle it. After following a few tutorials, I decided on a new layout with s ...

What is the correct way to update an array of objects using setState in React?

I am facing an issue where I have an array of objects that generates Close buttons based on the number of items in it. When I click a Close button, my expectation is that the array should be updated (removed) and the corresponding button element should dis ...

Display a loading screen while retrieving information in React Redux

I have two sections on the page - a collection of IDs on the left side and data display on the right. When the page loads for the first time, all data related to every ID is shown. However, users can only select one ID at a time to view its specific data. ...

The 'canvas' module could not be located in the system.Here are the required stacks:- /var/task/index.js- /var/runtime/index.mjs

I am currently developing a lambda function using the serverless framework. The function utilizes chartjs-node-canvas to create graphics, and everything runs smoothly on my MacBook when tested locally. However, when I deploy the function to AWS either dire ...

When working with React and trying to update data using the useEffect hook, I encountered an issue with an Array data. Unfortunately, using map or Object.keys(data).map did not produce the desired results. Can anyone provide guidance on

After using the useEffect hook to update the data, I noticed that the data is an array when inspected in the DEV tools. However, when attempting to traverse the data using the map function, an error stating 'data.map is not a function' is returne ...

Ways to retrieve the date of the chosen <td> cell in a calendar

Looking for a way to extract dates from the <td> elements selected by mouse? Here is my code snippet that highlights the TD upon selection: $(function () { var isMouseDown = false, isHighlighted; $("#schichtplan td") .moused ...

Is submitting with JQuery always a hit or miss?

Hey there, I'm currently working on a problem and could use some help. I seem to be having trouble getting inside my function for form submission in JQuery. Despite setting up console.logs, it appears that my code never reaches the first function. Can ...

Discover the XPath of a post on a Facebook page with the help of HtmlUnit

I am trying to fetch the xpath of a Facebook post using HtmlUnit. To better understand my goal, you can check out these two related questions: Supernatural behaviour with a Facebook page HtmlUnit commenting out lines of Facebook page To replicate my pro ...