Why won't the button's color change when I try clicking on it?

I am currently learning vue and facing some challenges. The code I have is supposed to change the button color when clicked, but it's not working as expected. Any advice on how to fix this issue would be greatly appreciated. Thank you!

let app = new Vue({
  el: '#app',
  data: {
    isActive: [true, false, false, false],
    movies: ['A', 'B', 'C', 'D'],
  },
  methods: {
    onClick(index) {
      this.isActive[index] = !this.isActive[index];
    }
  },
});
ul li {
  list-style: none;
}

.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <ul>
    <li v-for="(item, index) in movies">
      <button :class="{active: isActive[index]}" @click="onClick(index)">{{ item }}</button>
    </li>
  </ul>
</div>

Answer №1

When using arrays in Vue 2, the recommended way to update array indices is through the $set method.

let app = new Vue({
  el: '#app',
  data: {
    isActive: [true, false, false, false],
    movies: ['A', 'B', 'C', 'D'],
  },
  methods: {
    onClick(index) {
      this.$set(this.isActive,index,!this.isActive[index])
    }
  },
});
ul li {
  list-style: none;
}

.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <ul>
    <li v-for="(item, index) in movies">
      <button :class="{active: isActive[index]}" @click="onClick(index)">{{ item }}</button>
    </li>
  </ul>
</div>

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

The Drop Down Menu feature in Bootstrap is malfunctioning within the context of a NextJS project

I've built a NEXT.JS application using VS Code. The issue I'm facing is with the drop down menu in the navigation bar - it's not sliding down to display the menu when clicked. Here is the code I'm working with: const loggedRouter = () ...

Investigate the presence of a vertical scrollbar using JQuery or JavaScript

Within an HTML report, I have applied the style "overflow:auto" to allow for dynamic data filling. I am now facing the challenge of detecting whether a vertical scrollbar exists within the report. After scouring various forums for solutions, I came across ...

Getting the selected item from a dropdown menu and including it in an email

While working in React, I have successfully created a contact form that includes fields for name, email, and a message box. When the form is submitted, these three items are sent as expected. However, I am facing difficulty in sending a selected item from ...

The NPM Install process seems to be skipping certain files that were successfully installed in the past

When I first installed NPM Install in a folder, it created multiple folders and files: node_modules public src .DS_Store package.json package-lock.json webpack.config.js After that, npm start functioned perfectly. Now, as I embark on a new project for th ...

Utilizing jQuery/AJAX to interact with database in Django

Seeking assistance as I've tried multiple times with little success. Using the tango with Django book and various online examples, but no luck. Currently designing a 'Fake News' website with Django featuring a mini-game where users vote on w ...

Is it possible to extract an attribute value from a parent element using ReactJS?

https://i.stack.imgur.com/OXBB7.png Whenever I select a particular button, my goal is to capture the {country} prop that is linked to it. I attempted the following approach import React, { useState, useEffect } from 'react' import axios from &ap ...

`Where are functions housed in Vue when dealing with slots?`

When component A acts as the parent to component B, and B has a designated slot for content insertion, the question arises about the placement of a clickHandler. Should it be placed in A or in B? Is it possible to have both options implemented as long as ...

"Using the power of jQuery to efficiently bind events to elements through associative

I am attempting to link the same action to 3 checkboxes, with a different outcome for each: var checkboxes = { 'option1' : 'result1', 'option2' : 'result2', 'option3' : 'result3', }; ...

Tips for creating unique names for JSON data modification functions

I have some data stored in JSON format that I need to slightly rearrange before sending it to the client. What should I name the function responsible for this reordering? Is serializeSomething a suitable choice? From what I understand, serialization invo ...

I cannot seem to locate the module npm file

Currently, I am in the process of following a Pluralsight tutorial. The instructor instructed to type 'npm install' on the terminal which resulted in the installation of a file named npm module in the specified folder. However, when I attempted t ...

Combining relationships from various models in Laravel to streamline queries

Is it possible to combine two relationships into a single query from two separate models? class User extends Authenticatable { public function relazioneFollower() { return $this->belongsToMany(User::class, 'user_follower','follower ...

Generate a graph showcasing the frequency of character occurrences within a specific column of a .csv file

I'm currently working on creating a graph using d3.js What I need to accomplish is reading the some_column column in a .csv file and counting the occurrences of | to plot them accordingly on the y-axis. The line should be plotted based on the number ...

Unexpected JSON data submission

I am encountering an issue with JSON. Since I am not proficient in JSON, identifying the problem is challenging. Here is the JSP code snippet. $(document).ready( function(){ window.onload = dept_select; $("#sales_dept_id").change ...

What is the best way to conceal all input elements in a form?

I have been attempting to conceal input elements within my form by using the code snippet below. Unfortunately, it doesn't seem to be functioning as expected... <html lang="en"> <head> <title>example</title> < ...

Error: The JSONP request encountered an unexpected token, causing a SyntaxError

Asking for data using AJAX: $.getJSON('https://www.cryptocompare.com/api/data/coinsnapshot/?fsym=BTC&tsym=USD&callback=?', function(result) { console.log(result); }); Encountering an error: "Uncaught SyntaxError: Unexpected token :" ...

Optimizing Angular6 Pipe Filter Performance for Large Arrays

I have written a filter that retrieves a subset of items from a large array consisting of around 500 items. import { Injectable, Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'searchFilter' }) @Inject ...

tslint issues detected within a line of code in a function

I am a novice when it comes to tslint and typescript. Attempting to resolve the error: Unnecessary local variable - stackThird. Can someone guide me on how to rectify this issue? Despite research, I have not been successful in finding a solution. The err ...

Angular Application for Attaching Files to SOAP Service

I am currently utilizing soap services to pass XML data along with file attachments. While SoapUI tool works perfectly for this purpose, I want to achieve the same functionality through Angular6 in my project. Below is a snippet of my Xml code. <soap ...

Creating a searchable and filterable singleSelect column in the MUI DataGrid: A step-by-step guide

After three days of working on this, I feel like I'm going in circles. My current task involves fetching data from two API sources (json files) using the useEffect hook and storing them in an array. This array contains a large number of products and a ...

What causes a double fill when assigning to a single cell in a 2-dimensional array in Javascript?

I stumbled upon this code snippet featured in a challenging Leetcode problem: function digArtifacts(n: number, artifacts: number[][], dig: number[][]): number { const land: boolean[][] = new Array(n).fill(new Array(n).fill(false)) console.log ...