Utilize Vue to localize the click events of buttons on the webpage

I have a scenario where I have several buttons on a page, and when I click one to toggle its text, all of the buttons change. How can I utilize VUE to isolate functionality and make each button's @click event only affect the clicked button? In the code snippet below, you can see that every button changes when clicked, whereas I want only the text of the clicked button to change.

Here is an example from another post, full credit goes to:

change button while pressing it with vue.js

new Vue({
  el: '#app',
  data: {
    isFavorite: false
  },
  methods: {
    toggleFavorite() {
      this.isFavorite = !this.isFavorite;
    }
  }
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
  <button @click="toggleFavorite" v-show="!isFavorite">Add to favorites</button>
  <button @click="toggleFavorite" v-show="isFavorite">Delete from favorites</button>
 <button @click="toggleFavorite" v-show="!isFavorite">Add to favorites</button>
  <button @click="toggleFavorite" v-show="isFavorite">Delete from favorites</button>
</div>

Answer №1

Consider using a dictionary structure instead of a singular variable:

data() {
  return {
    favorites: {}
  }
},

Rather than toggling a boolean value, toggle a property within the object:

<button @click="toggleFavorite('itemA')" v-show="!favorites['itemA']">Add to Favorites</button>
<button @click="toggleFavorite('itemA')" v-show="favorites['itemA']">Remove from Favorites</button>

The toggle method:

methods: {
  toggleFavorite(item) {
    this.$set(this.favorites, item, !this.favorites[item]);
  }
}

Check out this demonstration if you need further clarification:

new Vue({
  el: '#app',
  data() {
    return {
      favorites: {}
    }
  },
  methods: {
    toggleFavorite(item) {
      this.$set(this.favorites, item, !this.favorites[item]);
    }
  }
})
<div id="app">
  <button @click="toggleFavorite('item123')" v-show="!favorites['item123']">Add to Favorites</button>
  <button @click="toggleFavorite('item123')" v-show="favorites['item123']">Remove from Favorites</button>

  <button @click="toggleFavorite('item456')" v-show="!favorites['item456']">Add to Favorites</button>
  <button @click="toggleFavorite('item456')" v-show="favorites['item456']">Remove from Favorites</button>
  
  <hr>
  
  <div v-for="y in 10" :key="y">
    <button @click="toggleFavorite(`item${y}`)" v-show="!favorites[`item${y}`]">Add to Favorites</button>
    <button @click="toggleFavorite(`item${y}`)" v-show="favorites[`item${y}`]">Remove from Favorites</button>
  </div>
</div>

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

Answer №2

The duplication occurs due to the similarity in v-show values. It may not be considered the best practice for Vue. You can opt for using v-if and v-else directives for data value comparisons, or simply update the text based on the value.

new Vue({
  el: '#app',
  data: {
    isFavorite: false,
    isFavorite2:false
  },
  methods: {
    toggleFavorite() {
      this.isFavorite = !this.isFavorite;
    },
    toggleFavorite2() {
      this.isFavorite2 = !this.isFavorite2;
    }
  }
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
  <button @click="toggleFavorite" v-show="!isFavorite">Add to favorites</button>
  <button @click="toggleFavorite" v-show="isFavorite">Delete from favorites</button>

<button @click="toggleFavorite2" v-show="!isFavorite2">Add to favorites 2</button>
  <button @click="toggleFavorite2" v-show="isFavorite2">Delete from favorites 2</button>
</div>

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

Updating JQuery function after window is resized

click here Currently, I am using slick-slider to showcase content in 3 columns by utilizing flexbox. The aim is to have the slider activated only on mobile view. This means that when the screen size shrinks down to mobile view, the 3 column flexbox transf ...

"Regarding compatibility with different browsers - IE8, Firefox3.6, and Chrome: An inquiry on

Snippet of JavaScript Code: var httprequest = new XMLHttpRequest(); var time = new Date(); if (httprequest) { httprequest.onreadystatechange = function () { if (httprequest.readyState == 4) { alert("OK"); } }; httprequest.open("GET", ...

Creating JSON arrays with JavaScript and jQuery

User Information var Users=[{"Id":1,"FirstName":"John"},{"Id":2,"FirstName":"Emily"}] Call Information var CallInfo=[{"Id":1,"PercentageCalls":"22 %","TotalTime":"60:24 minutes","PercentageTime":"0 %","AvgTime":"0:22 minutes"},{"Id":2,"PercentageCa ...

Enhance your Verold model object with engaging animations

Trying to utilize verold for animating 3D models through a script has been challenging. The proper usage of the verold API components seems unclear at the moment. A model has been successfully loaded into the scene with a script attached as an attribute o ...

What is the best way to pass a slot's @click event handler to its parent component, allowing the parent to bind it to an element using v-bind, similar to how it's done in Vuet

Initially, I make use of the <script setup> API for my project. In Vuetify components such as v-menu, there is a slot called activator where you have the ability to place a custom element as your dropdown "button" and bind the onClick listener by bi ...

Creating unsightly class names using Node.js

Is it possible to automatically create random and unattractive class names? For example, is there a tool or plugin that can substitute the .top-header class with something like .a9ev within my CSS code? It would also be ideal if the class name in the HTML ...

What is the best way to target the iframe within the wysihtml5 editor?

Currently, I am utilizing the wysiwyg editor called wysihtml5 along with the bootstrap-wysihtml5 extension. As part of my project, I am designing a character counter functionality that will showcase a red border around the editor area once a specific maxl ...

Scraping JavaScript Content Webpages with VBA

I'm attempting to extract a table from the Drainage Services Department website. I've written the VBA code below, but it doesn't seem to be working. I suspect that the issue lies in the fact that this particular table is generated using Java ...

Developing a dynamic table using HTML and JavaScript

I have a question that might sound silly, but I am trying to retrieve the HTML content from this particular website using JavaScript. The data I'm interested in is located at the center of the page within a dynamic table which does not change the URL ...

Is there a way to determine if a chosen date and time are prior or subsequent to the current date and time in an AngularJS environment?

When using a datepicker and timepicker, I have obtained a selected date and time. Now, I need to determine if this selected date and time is before or after the current date and time. For example, if the selected date is "Sat Dec 12 2015" and the selected ...

locating the truth value of the data in an array retrieved from MongoDB

When returning from the mongoose find() function, I need to ensure that is_reqestor = true is checked. However, when updating the document, I pass the id which needs to be updated. let filter = { is_reqestor: true } if (!is ...

Utilizing Angular 1.4.8 and lodash to effectively parse an array of objects with conditional parameters

DEVELOPER TOOLS Angular version 1.4.8, lodash version 4.0 SOLUTION IMPLEMENTATION After building on Derek's code contribution below, I have arrived at the following solution. It was necessary to make adjustments as using _.property() or _.map() ch ...

Tips on leaving comments inside a render <div>

Hey there! I'm facing an unusual issue in my React+Webpack project. Even though I marked a line as a comment using //, it still gets rendered in the HTML output. Strangely, I have never encountered this problem before and can't figure out what tr ...

Is it no longer possible to create custom linked Context Menus in Tabulator 5?

After using Tabulator for a few years, we have decided to switch over to Angular v13 and upgrade to the new Tabulator 5.x. In our previous implementation, we had set up a custom ContextMenu in the Table Column Definition like this: contextMenu: this.TableR ...

How to accentuate search results using Angular filters and conceal non-matching text?

Recently, I came across an interesting example of using Angular filter to highlight search results. It works well in highlighting the word 'suit', but I noticed that all non-matching text remains visible. If you'd like to see the example I ...

Switch or toggle between colors using CSS and JavaScript

Greetings for taking the time to review this query! I'm currently in the process of designing a login form specifically catered towards students and teachers One key feature I'm incorporating is a switch or toggle button that alternates between ...

Display a division upon choosing an option

I am working on a project that involves a selection menu in the form of a drop-down list. <select> <option id="one" value="something">Car</option> <option id="two" value="anything">Plane</option> </select> Also, I ...

Custom mute bot using Discord.js with the ability to specify duration and provide a reason

I'm creating a discord.js mute bot and encountering some issues with its functionality. Is there a way to program it so that when someone types the command !mute User, it automatically sets the time to 30min and the reason as No reason Specified. How ...

The width of Highcharts increases proportionally to the growth of the chart's width

I want to create a highcharts graph where the width increases as data points increase. Currently, I have: I am using vuejs with highcharts, but it should work similarly with jquery or other frameworks. <div class="col-md-6" style= ...

The div height adjustment peculiarities in IE7 and IE8 are causing quite a stir

I recently encountered a problem with my HTML/JS code that I thought was simple. The code is designed to expand the size of a div on mouseover and then collapse it back on mouseout. Here's how the code looks: CSS: .sign-in-up { position: absolut ...