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

Obtaining data from the following entry in JSON format using the Twitter API

I am currently developing a webpage that showcases user tweets, however I want to visually represent the gap in time between each tweet by displaying empty spaces. I have been struggling with the logic of how to achieve this task and haven't made muc ...

Is there a way to fetch and display property changes in Vue Material's md-dialog?

In the component hierarchy, there is a parent component containing a child, which further contains an md-dialog component. The dialog is opened from the parent component using the following code: ParentComponent.vue <template> <div> < ...

Steps for verifying that an object property contains the necessary properties

I have a component that receives an object as a prop: <foo :ob='object'></foo> Within the component, the prop is defined like this: props: { ob: { type: Object, required: false, default: {} } } Typically, the expe ...

Finding the inverse value from the Lodash get() function

My current approach involves utilizing the lodash get() method to retrieve values from an object. However, there are instances where I need to obtain negated values. Unfortunately, simply applying a negate symbol or negate method after retrieving the valu ...

Is there a way to place my searchbox in the top right corner of the page?

I am currently working on creating a search function for my list of products. However, I have encountered an issue where the searchBox is not appearing in the top right corner as intended. Despite trying various solutions, I have been unsuccessful in movin ...

Applying a class to an element in VueJS is not functioning as expected

My goal is to assign the class .testcolor to the div element when testvalue is true, and apply no class when it's false. I encountered an issue where the getClass method does not get called when added to :class attribute, but works fine when called f ...

Serve static files from parent directories using Express.js

Currently facing some issues serving static files with expressJs. Directory structure: public css lib src views home index.html server.js In my index.html, all assets are prefixed with a leading slash. Static file setup: app.use(express.static ...

Create styles for each component based on their specific props when designing a customized Material-UI theme

I am having trouble styling the notchedOutline of a disabled <OutlinedInput /> in my custom MUI theme. My goal is to make the border color lighter than the default color when the input is disabled. Here is what I have attempted so far: const theme = ...

Storing multiple email addresses in an array using an HTML input element

I have a small React Bootstrap form where I am trying to save multiple email addresses entered by the user into an array. However, when I use onChange={()=> setEmails(e.target.value as any} it stores them in string format like this --> [email p ...

The Redux store has been modified, yet the changes are not reflected in the

In my Posts.js component, I am mapping every object in the posts array. Within this function, I attempt to filter all notes that have the same post_id as the id of the current mapped post object and store them in a variable called filteredNotes. I then pas ...

How to dynamically generate data with exceljs

Currently, I am attempting to download JSON data into an Excel spreadsheet. One of my requirements is to insert an image in cell a1 and then bold the headers. The code snippet below was sourced from Google; however, I need to populate the data dynamically ...

Utilizing Think ORM seamlessly across multiple files without the need to repeatedly establish a connection to the

I'm facing a situation where I have numerous models for thinky, and in each file I am required to create a new object for thinky and connect it multiple times due to the high number of models. var dbconfig = require('../config/config.js')[& ...

Locate and modify a specific element within an array of objects

Currently, I am working with an array that looks like this: arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}]. However, I need to add a condition to the array. If ...

Troubleshooting problems during Vue setup

Just diving into Vue development and hitting a roadblock. Here's what I've done so far: I followed the installation guide on the Vue 3 documentation, which can be found at the following link: https://v3.vuejs.org/guide/installation.html#npm I ...

Do you need to redeclare the type when using an interface with useState in React?

Take a look at this snippet: IAppStateProps.ts: import {INoteProps} from "./INoteProps"; export interface IAppStateProps { notesData: INoteProps[]; } and then implement it here: useAppState.ts: import {INoteProps} from "./interfaces/INo ...

Troubleshooting problem with Ajax responseText

Can an ajax responseText be received without replacing the existing content? For instance: <div id="content"> <p>Original content</p> </div> Typically, after running an ajax request with a responseText that targets id="conten ...

Having difficulties updating a value in Angular through a function written in HTML- it refuses to update

<select ng-model="currentTimeStartHour" style="width: 33%" ng-change="UpdateTime(this)"> <option ng-repeat="hour in choices" value="{{hour.id}}">{{hour.name}}</option> </select> Somewhere else on the page... {{totalHours}} Whe ...

Display an Asterisk Icon for md-input fields with lengthy labels

Documentation states that md-inputs add an asterisk to the label if it is a required type. However, when input containers have width constraints and long labels, the label gets truncated and the asterisk becomes invisible. From a user experience perspectiv ...

"Transmitting a message with socket.io upon establishing connection

Currently getting the hang of socket.io and giving it a try. I have a straightforward app where clicking the display button shows an image on the screen in real time. I have a couple of questions. Firstly, my main concern is regarding the synchronization ...

Is the Vis.js network function ready to go?

Utilizing the Vis.js network library to display graphs and am curious if there is a dedicated finishedLoading event available for this object? Any suggestions or insights are appreciated! ...