Switching class names on click in Vue.js

When clicked, I would like to toggle the class name from "product fav" to "product fav active". The change should be conditional; if the class is already active, it should be removed.

Answer №1

Make sure to structure it like this:

<template>
  <main>
    <div class="favorite item" :class="isActive ? 'active' : ''" />
    <button @click="isActive = !isActive" />
  </main>
</template>

Remember to utilize v-bind:class. (Using :class is the shorthand method.)

Answer №2

You have the option to control a boolean variable called isActive, which determines the class.

HTML:

<div id="app"></div>
<script type="text/x-template" id="test-template">
    <div :class="{'active':isActive}" @click="toggleClassActive">Toggle active class</div>
</script>

Vue:

var vueInstance = new Vue({
    el: '#app',
    template: '#test-template',
    data: {            
      isActive: false
    },
    mounted: function () {},
    computed: {},
    methods: {
        toggleClassActive () {        
        this.isActive = !this.isActive;
      }
    }
});

Check out the jsfiddle link

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

Problems arising in AWS integration with Django backend and Vue.js frontend

My Django backend is currently deployed on AWS Elastic Beanstalk with default settings and auto-scaling environment type set to single instance. Meanwhile, the Vue.js frontend is being hosted on AWS S3, configured with CloudFront and now running on HTTPS f ...

Sliding an image from the left side to the right, and then repeating the movement from left to right

I am currently working on a CSS effect for some images. My goal is to have an image appear from the left side, move towards the right side, then reappear from the left and repeat this cycle. I managed to achieve this using the code below: @keyframes sli ...

`Incorporate concurrent network requests in React for improved performance`

I am looking to fetch time-series data from a rest service, and currently my implementation looks like this async function getTimeSeriesQuery(i) { // Demonstrating the usage of gql appollo.query(getChunkQueryOptions(i)) } var promises = [] for(var i ...

Passing a value through jQuery Ajax when selecting an option (onchange) to store in a PHP variable on the same page without

How can I retrieve the selected value using PHP and update a specific div element with it? <div id="test"> <?php if (isset($_POST['sweets'])) { ob_clean(); echo $_POST['sweets']; exit; } ?> ...

Ways to send a property directly from the parent to every child component?

Here's an example: <main-parent :data1="hello" :data2="world"> </main-parent> MainParent.vue: <template> <div> <child1 :info1="data1"></child1> <child2 :info2="data2"></child2> </div> ...

What is the most efficient way to execute useEffect when only one specific dependency changes among multiple dependencies?

My main objective is to update a state array only when a specific state (loadingStatus) undergoes a change. Yet, if I include solely loadingStatus as a dependency, React throws an error requesting all dependencies [loadingStatus, message, messageArray, set ...

Retrieve JSON data using AngularJS

Can someone guide me on how to make a GET request to my API endpoint and handle the JSON response in my code? Sample Controller.js Code: oknok.controller('listagemController', function ($scope, $http) { $scope.init = function () { ...

Having an issue with TypeScript and React where the onChange event on the <select> element is only setting the previous value instead of the current value when using the useState hook

I'm currently developing a scheduling web tool. One of the key features I'm working on involves calculating the total hours between two selected times, startTime and endTime. These times are chosen via a form and stored using the useState hook: ...

How can I generate a checkbox in a database with a field that allows for enabling and disabling?

I am looking to design a table that includes questions, checkboxes, and text boxes. All the questions are stored in a database and called through an array. In addition, I want to create disabled textboxes that become enabled when their corresponding checkb ...

What are the steps to implement timer control in Ajax using JavaScript?

Hello, I have been trying to establish communication with the server through my application. To achieve this, I made a call to the webservice using AJAX. Now, I am looking to incorporate a time interval in AJAX. Can anyone kindly provide guidance on how ...

React.js - Implementing a Delayed Loading Indicator to Prevent Flickering

How do I implement a loading indicator in React that only appears if the loading state is true for over 1 second, and if it resolves before 2 seconds, show the indicator for at least 1 second? In Angular JS, there was a similar question with 5 conditions: ...

Make sure the auto import feature in TypeScript Visual Studio Code Editor is set to always use the ".js" extension

At times, the auto-import completion feature includes the .js extension, but inconsistently. When this extension is missing in the TypeScript source, the emitted JavaScript file may encounter runtime issues like module not found error since the tsc compile ...

Emulating a Javascript API request

I'm looking to practice simulating API calls for a VueJS application. Currently, I am fetching data from a hardcoded JSON file that I've created. Within my App.vue: <template> <p>{{ teams.yankees.city }}</p> // Output will b ...

The utility of commander.js demonstrated in a straightforward example: utilizing a single file argument

Many developers rely on the commander npm package for command-line parsing. I am considering using it as well due to its advanced functionality, such as commands, help, and option flags. For my initial program version, I only require commander to parse ar ...

Keep fancybox items in their designated spot

When the window is opened at full size, everything looks fine. However, when you resize the window horizontally, the thumbnails shift and disappear. I want them to remain fixed in their position like the large pop-up image so that users can still see them ...

JavaScript is proving to be uncooperative in allowing me to modify the

Despite searching through previously asked questions, I have been unable to find a solution to my issue. I am struggling with changing an image source upon clicking the image itself. The following is a snippet of my HTML code: <img id="picture1" oncli ...

Rearranging columns in Bootstrap 4 beta across multiple containers

Sorry for any language issues in my English. This shows my regular grid: ------------------------------- | A | B | C | ------------------------------- | D (horizontal menu) | ------------------------------- Is it possible to d ...

The server failed to respond to the Angular HTTP request

To store data in my database, I have created a function in my component.ts file that invokes a service: ajoutText(newtext: String) { this.dataService.sendtext(newtext); } On the HTML side, it looks like this: <form class="form"> <mat-form-f ...

Error: Unable to access the 'width' property of an undefined value - Nuxt JS and Canvas

I am new to using Vue JS and trying to run a sketch on the canvas element in Nuxt JS, but encountering some issues. While there are no errors in VS Code, there is an error showing up in the browser console: client.js?06a0:84 TypeError: Cannot read propert ...

Incapable of stacking one canvas on top of another

I'm new to javascript and looking for help with positioning a canvas element behind another. The code I have may be a bit messy, so any assistance is greatly appreciated. My goal is to have the canvas named "myCanvas" appear behind "coinAnimation". Th ...