What is the process for updating the class of the target button?

I am new to using Vue and struggling to achieve a specific functionality. I have multiple buttons and I want to ensure that only one button can be selected at a time. Currently, I have tried implementing it with the following code:

:class="isActive ? 'on' : 'off'"
v-on:click ="isActive = !isActive"

However, this approach activates all buttons simultaneously. I realize that I need to somehow differentiate between the target button and the non-target ones but I'm unable to figure out how to do this. Can you provide me with some code examples on how to achieve this?

data() {
        return {
            isActive: true,
            color: ‘’,
        };
    },
<template>
      <div id="btn-box">
        <button
          type="button"
          class="btn off"
          @click="component='BorderLeftComonent', toggleShowPopup()">
          <div
            style="padding: 0 5px; width: 25px; margin: 0 auto; font-size: 25px;"
            :style="{ 'border-left': `4px solid ${color}` }">A</div>
        </button>
        <button
          type="button"
          class="btn off"
          @click="component='TextBalloonComponent'">
            <div
            class="bubble"
            style="margin: 0 auto; width: 25px; font-size: 25px;">A</div>
        </button>
        <button
          type="button"
          class="btn off"
          @click="component='DashedComponent'">
          <div
            style="border: 4px dashed #f5d018; margin: 0 auto; width: 45px; font-size: 25px;">A</div>
        </button>
      </div>
</template>

Answer №1

Incorrect Syntax:

:class="isActive ? 'on' : 'off'"
v-on:click ="isActive = !isActive"

Corrected Syntax (using shorthand method):

:class="{ 'on': isActive, 'off': !isActive }"
@click="isActive = !isActive"

Alternatively, you can use this syntax and refer to the example below:

:class="{ 'on': isActive, 'off': !isActive }"
@click="toggle"

Implement the @click event toggle within the methods section like this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <!-- these buttons have `:class` binding and `@click` event -->
  <button :class="{ 'on': isActive, 'off': !isActive }" @click="isActive = !isActive">Toggle</button> OR
  <button :class="{ 'on': isActive, 'off': !isActive }" @click="toggle">Toggle</button> OR

  <!-- these buttons just have `@click` event -->
  <button @click="isActive = !isActive">Toggle</button> OR
  <button @click="toggle">Toggle</button> OR

  <!-- these buttons do not (have class and event binding) do anything -->
  <button>Toggle</button> OR
  <button>Toggle</button>

  <p v-if="isActive">{{ message }}</p>
</div>

<script>
  let app = new Vue({
    el: '#app',
    data: {
      message: 'Hello Vue.js!',
      isActive: true,
    },
    methods: {
      toggle() {
        this.isActive = this.isActive ? false : true
      }
    },
  })
</script>

<style scoped>
  /*add some basic styling for your classes*/
  
  button {
    padding: 0.5em;
    border-radius: 5px;
    color: hsl(205, 46.5%, 73.5%);
    background-color: hsl(205, 14%, 28%);
  }
  
  .on {
    color: green;
  }
  
  .off {
    color: red;
  }
</style>

Answer №2

Implement the v-for directive to loop through an array of button objects, each containing its own isActive property that can be toggled using the onclick event.

<button
      v-for="(button, index) in buttons"
      :key="index"
      :class="button.isActive ? 'on' : 'off'"
      @click="button.isActive = !button.isActive"
    >
      <div :class="`btn btn-${button.type}`">{{ button.label }}</div>
</button>
data() {
    return {
       buttons: [
        {
          label: "A",
          isActive: false,
          type: "border-left",
        },
        {
          label: "B",
          isActive: false,
          type: "text-balloon",
        },
        {
          label: "C",
          isActive: false,
          type: "dashed",
        },
      ],
    };
  }
<style scoped>
.btn {
  padding: 0 5px;
  width: 25px;
  margin: 0 auto;
  font-size: 25px;
}
.btn-border-left {
  border-left: 4px solid #f55;
}
.btn-dashed {
  border: 4px dashed #f5d018;
  width: 45px;
}
</style>

Answer №3

If you are looking for a button group, a common component in UI libraries, check out this one at this link.

As an illustration, the example below showcases 4 buttons aligned next to each other, with each button getting highlighted upon clicking, as shown in the GIF provided.

https://i.stack.imgur.com/fg1la.gif

In your code snippet, there is a property (named "text" in this case) that indicates which button is currently selected. Here's a snippet borrowed from the aforementioned link:

<v-btn-toggle
    v-model="text"
    tile
    color="deep-purple accent-3"
    group
  >
    <v-btn value="left">
      Left
    </v-btn>

    <v-btn value="center">
      Center
    </v-btn>

    <v-btn value="right">
      Right
    </v-btn>

    <v-btn value="justify">
      Justify
    </v-btn>
  </v-btn-toggle>

Hope this addresses your query effectively!

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

Darkness prevails even in the presence of light

I'm currently in the process of developing a game engine using ThreeJS, and I have encountered an issue with lighting that I need assistance with. My project involves creating a grid-based RPG where each cell consists of a 10 x 10 floor and possibly ...

What is the best way to gather Data URI content through dropzone.js?

I am currently utilizing Dropzone for its thumbnail generation feature and user interface. However, I am only interested in using the thumbnail generation ability and UI and would prefer to collect all the data URIs myself and send them to the server via a ...

Increasing values in Mongoose using $inc can be done by following these steps

I've been struggling to increment a field value using $inc in my code. My schema looks like this: var postSchema = mongoose.Schema({ title : { type: String, required: true }, body : { type: String, default: '' }, coun ...

Bring in Bootstrap and the Carousel plugin using Webpack Encore

Currently, I am tackling an issue within my Symfony project that involves Webpack Encore and the loading of Bootstrap and the Carousel plugin. The problem may stem from how I import Bootstrap, as it seems to partially work when I import the file like this ...

Utilize Node.js driver to export a Mongo collection into a JSON file

How can I export a MongoDB collection to a JSON format using the Node.js driver and fs.writeFile? ...

Exploring the world of Typescript and Angular Filter functionalities

I am looking to utilize one of my Angular Filters in my controller as a function. I came across a solution on this page: How to use a filter in a controler The last answer provided exactly what I needed, so I implemented it in my JS code: var MyFunc ...

Communication between the Node development server and the Spring Boot application was hindered by a Cross-Origin Request

Here is the breakdown of my current setup: Backend: Utilizing Spring Boot (Java) with an endpoint at :8088 Frontend: Running Vue on a Node development server exposed at :8080 On the frontend, I have reconfigured axios in a file named http-common.js to s ...

What is the best way to transfer the content from a tinyMCE textarea editor to an inner controller using Symfony3 and Ajax

I have two small rich text editors identified as #homepage and #thankyoupage. My goal is to submit the content of these TinyMCE text areas to a Symfony controller. Below is my front-end implementation: https://i.stack.imgur.com/TE1Ys.jpg Currently, I am ...

Exploitable Weakness Found in NestJS Version 8.4.5

After running npm audit on my npm package recently, I encountered an error that is related to the dicer package, widely used by NestJS. I have looked for solutions online but haven't been able to find any fixes so far. Has anyone else managed to reso ...

Selection auto-closing feature

I am currently working on a button that generates a dropdown menu with various categories to choose from. I would like the dropdown to automatically close when I click outside of it, similar to how a lightbox or modal popup works on a webpage. Currently, I ...

Animation failing to be queued properly

Here is a snippet of code that moves a heading icon back and forth when you hover over the heading: jQuery('h1.heading').hover( function(){ $icon = jQuery('.heading-icon', this); if( ! $icon.is(':animated') ){ ...

Sharing methods between controllers in AngularJS

After coming across this insightful article on Angular validation, I decided to implement it in my project. The validation is functioning perfectly, but I am struggling to access methods in other controllers upon successful form validation. Despite trying ...

How can you call a function in ExpressJS that is located in a different file?

I am having trouble with my UserController and database configuration file db.js. I am trying to make a function in the UserController access a function in db.js. In my UserController, I have included var db = require('../config/db'); and within ...

The HTML table inexplicably displays a random comma out of nowhere

When working on my HTML table, I noticed that it was rendering a comma unexpectedly. I am using Nodemailer and SMTP Google server, and I suspect the issue lies within the HTML code. However, I am struggling to identify the exact problem. https://i.stack.i ...

What is the best way to integrate a PHP page with its own CSS and JavaScript into a Wordpress page?

I'm facing a challenge with integrating a dynamic PHP table into my WordPress page. Despite working perfectly when opened locally, the CSS and JavaScript used to create the table are not functioning properly when included in a WordPress page via short ...

Electron.js issue: ipcRenderer and ipcMain leading to a white screen problem

I am currently working on a desktop application using Electron, Vue, and Vuetify. However, I have encountered an issue where sending data from the rendererProcess to mainProcess using IPC results in a white blank screen. I'm unsure of what is causing ...

'AngularJS' filtering feature

I am dealing with an array of objects and I need to extract a specific value when a key is passed in the 'filter' function. Despite my best efforts, the controller code snippet provided below returns an undefined response. Can someone please assi ...

Manipulate the presence of THREE.Points in a three.r84 scene by adding or removing them

I recently upgraded from three.js version 71 to version 84 and encountered a problem with updating points in the scene. Previously, with THREE.PointCloud, it was simple to add and remove points as needed like so: function updatePoints(newData) { geom ...

Exploring the functionality of the JavaScript Date constructor in relation to

Will using new Date('2015-01-01') provide me with the exact moment equivalent to 2015-01-01T00:00:00Z? ...

Using jQuery, selectively reveal and conceal multiple tbody groups by first concealing them, then revealing them based on

My goal is to initially display only the first tbody on page load, followed by showing the remaining tbody sections based on a selection in a dropdown using jQuery. Please see below for a snippet of the code. //custom JS to add $("#choice").change(func ...