In Vue.js, easily toggle classes with a click

I am having trouble figuring out how to apply a class to a button and then change it to another class after it is clicked. The idea is to have multiple buttons that serve as filters, allowing the user to select only one at a time with the selected button being highlighted. I can get the highlighting part to work, but I'm struggling with removing the initial class to change the text color using v-bind.

Here is a link to the JSFiddle without the "notactive" class added, as I am still trying to find the best solution.

JSFiddle

new Vue({
  el: '#vue',
  data: {
    selected: ''
  }
})
.highlight {
  color: green;
  font-size: 16px;
  border: 0;
  background: 0;
}


.notactive {
 color: grey;
 border: 0;
 background: 0;
 font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vue">
  <button @click="selected = 1" :class="{highlight:selected == 1}">Button1</button>
  <button @click="selected = 2" :class="{highlight:selected == 2}">Button2</button>
  <button @click="selected = 3" :class="{highlight:selected == 3}">Button3</button>
</div>

Answer №1

Initializing a new Vue instance with data for selecting different buttons:
.highlight {
  color: green;
  font-size: 16px;
  border: 0;
  background: 0;
}

.notactive {
  color: grey;
  border: 0;
  background: 0;
  font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vue">
  <button @click="selected = 1" :class="{highlight:selected == 1, notactive:selected !== 1}">Button1</button>
  <button @click="selected = 2" :class="{highlight:selected == 2, notactive:selected !== 2}">Button2</button>
  <button @click="selected = 3" :class="{highlight:selected == 3, notactive:selected !== 3}">Button3</button>
</div>

Answer №2

If I understand correctly, the solution to your question involves adding another entry for the notactive class in your class binding:

<div id="vue">
 <button @click="selected = 1" :class="{highlight:selected == 1, notactive:selected !== 1}">Button1</button>
 <button @click="selected = 2" :class="{highlight:selected == 2, notactive:selected !== 2}">Button2</button>
 <button @click="selected = 3" :class="{highlight:selected == 3, notactive:selected !== 3}">Button3</button>
</div>

Check out the updated fiddle here - https://jsfiddle.net/chrismarx/ptk247wz/

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

Display content in .innerHTML continuously with Javascript and a while loop

I'm currently learning how to implement while loops in my code. I understand the concept quite well, but I'm facing some difficulty in using a while loop to write text repeatedly to an HTML element. var userText = prompt("Enter the text you wa ...

Performing computations within a loop and ways to retrieve the total of the elements in Vue.js

Starting out as a newcomer to JavaScript, I am seeking guidance on how to effectively incorporate it into my current project. I'm tasked with creating a sophisticated financial calculator within my already existing PHP financial instrument. The goal ...

Connecting Vue.js components together

I have two separate components - one for viewing data and another for editing the same data. The viewing component contains labels and paragraphs, while the editing component includes inputs and textareas. Both components are fed the same data object. Is ...

Personalized features to enhance Angular control

I'm in the process of dynamically loading a controller based on various values and I'm looking for the most practical way to accomplish this task. Details below. I'm attempting to access the value of the data-post-id attribute within the co ...

In Javascript, have an audio clip play every 30 seconds

My webpage has a unique feature - it automatically plays a short audio clip as soon as the page loads. This functionality is achieved using a special audio player called nifty player. Here is the code snippet for embedding the player: <object classid= ...

Steps to combine multiple arrays into a unified array:1. Begin by allocating a

To form a league table, I have multiple individual arrays filled with data. In order to sort them by points, I want to merge these arrays into a single array called "teams". However, I am unsure if there is a function available to achieve this specific f ...

The attempt to create the property 'and_ff' on the string 'and_chr 89' has failed

Encountering an issue with a Lambda function, I receive an error that does not occur when running the same code within an Express app. I'm puzzled. Data returned by caniuse.getLatestStableBrowsers(); [ 'and_chr 89', 'and_ff 86& ...

React-select fails to trigger form submission when the Enter key is pressed

Currently, I am utilizing Formik and React-Select in my project, and I'm hoping to enable the form submission by pressing enter while focused on a select input. Interestingly, when I'm focused on any other input field and press Enter, the form s ...

Is there a way to set a default CSS background image using JavaScript in case the specified

When working with regular CSS, I can easily set a fallback image using this code in case the primary image is not available: .container { background-image: url(pics/img.webp), url(pics/img.png); } But when it comes to setting styles in JavaScript (such ...

Tips on saving stimulsoft report js onto a server using Angular

I am working on a report designer component and have assigned a method to the onSaveReport event. However, I am encountering an issue where the member of my component is showing as undefined. options: any; designer: any; public document: Report ...

Retrieving data from a cell within an HTML table by utilizing the children[] method

I've been trying to extract a specific value from the HTML of a cell in an HTML table. I attempted to use the .rows parameter initially, but that resulted in the JavaScript halting at the line involving .row. Currently, I have resorted to assigning an ...

JavaScript's Set data structure does not allow for the storage of strings

As I retrieve a collection of data consisting of questions from mongoDB, I am attempting to place them in a random question set. However, the set is not accepting any input and is returning empty. module.exports.java = async (req, resp) => { // const ...

The issue lies with Mongoose's inability to convert a string into an object key

When making an ajax call, I pass the object below to Mongoose: {category: 'name', direction: 1} To sort the query results using Mongoose, I use the following code: Site.find(query).sort(sortBy) Prior to this call, I need to format the object ...

TypeScript does not perform type checking on arrays created using the Array() constructor and filled with the fill method

Using TypeScript version 2.4.2, compiled with the --target ES6 option has interesting results. For example, when using this line of code: var coins: { coin: number}[] = [1,1,1] TypeScript throws an error: Error TS2322: Type 'number[]' is no ...

download image using React map method

I am trying to transfer an image from one useState variable to another when it is clicked const [photos, setPhotos] = useState([]); useEffect(() => { setPhotos(PhotoArray); }, []); This is the source image that I am using: export const PhotoArr ...

Using JavaScript import may encounter issues when trying to access the same file or a different file

When importing something and using it, there are certain scenarios where it may not work as expected. For example: <html> <body> <button onclick="foo()">Click Me</button> </body> <script type="module"> ...

Responsive design element order rearrangement

My code example is as follows: <div class="info-container"> <span class="item1">item1</span> <a class="item2" href="#">item2</a> <a class="item3" href="#">item3</a> </div> I want to rearran ...

Utilizing the jQuery slideToggle method on the specified target element

I'm encountering an issue with jQuery slideToggle, and here's the code I have: $(".dropdownmainmenu").click(function(){ $(this).children(".showmenu").slideToggle(); $(this).toggleClass("activemainmenu"); $(this).find(".showarrowmainmen ...

The Bootstrap navigation menu is functioning properly when opening, but has an issue when attempting

Creating a mirrored version of an HTML file using NuxtJS, I've included the following code snippet in the Navbar component for my NuxtJS project. <template> <section id="navigation-menu" class="menu menu3 cid-sLhoPz7Ycg" ...

Leveraging information from a single controller for another

I am currently developing a website using MEAN stack. I am facing an issue with passing data from one controller to the next. My goal is to transfer a selected option value to the next page. Here is the section with the select box: <div class="plumber ...