Activate one button out of several in Vue by clicking on it

I am working on a functionality where I have three buttons. When one button is clicked, it should become active while the other two become inactive. However, in my current code, all three buttons are changing together on the click event. Is there a more elegant solution to this issue rather than creating separate values like isActive1, isActive2, and isActive3 for each button?

<div class="btn-group" role="group">
    <button type="button" :class="getActiveClass()" v-on:click="getWeather('Misto Kyyiv'); isActiveBtn = !isActiveBtn">Kyiv</button>
    <button type="button" :class="getActiveClass()" v-on:click="getWeather('London'); isActiveBtn = !isActiveBtn">London</button>
    <button type="button" :class="getActiveClass()" v-on:click="getWeather('New York'); isActiveBtn = !isActiveBtn">New York</button>
</div>
data: function() {
    return {      
        isActiveBtn: false
    }
}, 
getActiveClass() {
    if (this.isActiveBtn) {
        return "btn btn-secondary active";
    } else {
        return "btn btn-secondary";
    }
}

Answer №1

To optimize your code, I recommend storing the currently active city as part of your data. In the function getActiveClass, you can pass and compare the ID of a button to the currently active ID, then set the class accordingly.

<div class="btn-group" role="group">
  <button type="button" :class="getActiveClass('Kyiv')" v-on:click="getWeather('Misto Kyyiv'); activeId = 'Kyiv'">Kyiv</button>
  <button type="button" :class="getActiveClass('London')" v-on:click="getWeather('London'); activeId = 'London'">London</button>
  <button type="button" :class="getActiveClass('New York')" v-on:click="getWeather('New York'); activeId = 'New York'">New York</button>
</div>
getActiveClass(id) {
  if (id === this.activeId) {
    return "btn btn-secondary active";
  } else {
    return "btn btn-secondary";
  }
}

Answer №2

To tackle this issue, consider implementing three data properties as one approach. Alternatively, you could introduce a prop called activeBtn to store the name or index of the currently active button. In that case, modifications will need to be made to the getActiveClass method so that it can receive an argument containing the name or index of the button.

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

Anticipating the fulfillment of promises with the power of Promises.all

I have adopted the code found here for loading multiple .csv files. Upon successful loading of these files, my intention is to then render a react component. Below is the method located in datareader.js that I am currently working with. I am exploring the ...

Display PDF file retrieved from the server using javascript

I am currently working on a web application using JavaScript, jQuery, and Node.js. I need to receive a PDF file from the server and display it in a new browser window. While I believe I have successfully received the file on the client side (the window sh ...

Assign characteristics to the button, however it will only activate after being clicked twice

The button I created with some bootstrap attributes is not working properly on the first click. To resolve this, I initially called the function in onload and then again on the button click. However, I am now unable to do so and am seeking alternative solu ...

Different style conditions in VueJS

I'm attempting to alter the appearance of my div that has the class "objectsList". I am looking to change the style if my SearchFiltersToggle is false AND at the same time if my window's width is less than 1200px. It functions when I only specif ...

Panoramic viewer for Three.js with multi-resolution image support

Is there a way to incorporate a three.js panorama viewer with multi-resolution images similar to pannellum? Check out pannellum's example here: . You can find the current code using three.js here:(//codepen.io/w3core/pen/vEVWML). Starting from an e ...

The edges of the cubemap in THREE.js appear murky

I am attempting to create a black skybox with white dots (stars) in three.js. However, due to the perspective effect, the dots appear darker in the corners where they are further away (as they get smaller and dimmer). Is there a way to make the appearance ...

Transmitting information from the front-end Fetch to the back-end server

In my stack, I am using Nodejs, Express, MySQL, body-parser, and EJS. My goal is to trigger a PUT request that will update the counter by 1 when a button is pressed. The idea is to pass the ID of the clicked button to increment it by 1. app.put("/too ...

Is there a way to replicate the functionality of $(document).ready for dynamically loaded AJAX content?

$(document).ready(handler) is triggered once the DOM has finished loading. However, if new content containing a $(document).ready(handler) function is added to the page via AJAX, this function will be executed immediately according to the jQuery API. It&ap ...

Presenting a video from local storage (Vue)

Currently, I'm tackling a Vue project that requires displaying a video from a local directory. <video width="320" controls src="internal_path.mp4" type="video/mp4" height="240" autoplay muted loop> I've implemented the code snippet to dis ...

Clear previous loop data in PHP

I have a "show recent" pictures div on my website that I want to refresh every 20 seconds to display a new picture. However, the issue is that my current ajax call refreshes instantly instead of after 20 seconds and it fails to delete the previous data, re ...

What benefits and drawbacks come with setting up JS libraries in resource files compared to package.json?

Configurations for JavaScript libraries such as Babel, Nyc, Eslint, and many others can be specified in resource files or within the package.json. For example, Babel can be set up in a .babelrc file or through a babel entry in the package.json. What are ...

Debugging a script designed to output a value of 1 if the Mean equals the Mode, and 0 if they are not equal

As a beginner coder, I am working on a code that should return 1 if the mean is equal to the mode and 0 otherwise. However, my current code only outputs 0 even when it should be returning 1. Any guidance or assistance in identifying where I may have made ...

Vuetify props are not getting properly registered (Version 3.2.13 of Vue and Vuetify nightly 3.0.0)

<v-btn icon color="white" > <v-icon>mdi-account</v-icon> </v-btn> Issue with vuetify button not displaying icon using prop package.json { "name": "project", "version": "0.1.0& ...

Are elements such as String and Number to be classified as "constructor functions" within JavaScript programming?

After spending a few weeks poring over tutorials, I've finally uncovered an interesting fact. When using the prototype property on a constructor function, the key/value pairs on that prototype property are actually copied to the proto property of the ...

Error encountered while trying to display the react-bootstrap table

I am having trouble rendering sample data using react-bootstrap tables. Every time I try, I encounter the error: TypeError: Cannot read property 'filter' of undefined I've searched on various platforms and visited multiple links, but I ca ...

Puppet Master: Retrieve the inner content

Is there a way to retrieve the innerHTML or text of an element? Or even better, how can I click on an element with a specific innerHTML? The approach in regular JavaScript would be as follows: let found = false; $(selector).each(function() { if (found ...

Styling <Link> component with styled-components: A step-by-step guide

Utilizing the Link component from @material-ui/core/Link in my TypeScript code was initially successful: <Link href="#" variant="body2"> Forgot? </Link> However, I am exploring the transition to styled-components located in a separate file. ...

My email submission function is malfunctioning

my contact form in my website is not working properly. I have tried troubleshooting the issue by checking the contact.php file but it doesn't seem to be the problem. The script that I am using for the form submission is shown below: <!--Contact U ...

I am looking to display the results table on the same page after submitting a form to filter content. Can you provide guidance on how to achieve this?

Could someone provide guidance on how to approach the coding aspect of my current issue? I have a search form that includes a select form and a text box. Upon submission, a table is generated with results filtered from the form. Should I utilize a sessio ...

How to insert an HTML element in between multiple list items using jQuery

I have a variety of div elements that I want to group together using jQuery's append method: Here are the initial div elements: <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div& ...