Utilize multiple buttons to toggle with v-if condition

Here's the code snippet I'm working with:

<div class="flex justify-between flex-wrap">
     <div v-for="kink in kinks.data" :key="kink.id">
           <button type="button" :class="enabled ? 'bg-red-600' : 'bg-gray-600'" class="m-1 my-2 inline-flex items-center px-3.5 py-2 border border-transparent text-sm leading-4 font-medium rounded-full shadow-sm text-white hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500"> {{ kink.name }}</button>
     </div>
</div>

I have a data point kinks: []. The goal is to let users click on multiple buttons, store the ID of each clicked button in a new data point, and toggle the color of the button between gray and red when clicked (up to 10 times).

This is new territory for me, and I'm struggling to figure out how to make it work. Any guidance or assistance would be greatly appreciated!

Answer №1

Here is a possible solution based on your explanation:

new Vue({
  el: "#demo",
  data() {
    return {
      kinks: {data: [{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}, {id: 4, name: 'd'}, {id: 5, name: 'e'}]},
      selected: []
    }
  },
  methods: {
    setBtn(id) {
      if (this.selected.includes(id)) {
         this.selected.splice(this.selected.findIndex(i => i === id), 1)
      } else this.selected.push(id)
    },
    checkBtn(id) {
      return this.selected.includes(id)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" integrity="sha512-wnea99uKIC3TJF7v4eKk4Y+lMz2Mklv18+r4na2Gn1abDRPPOeef95xTzdwGD9e6zXJBteMIhZ1+68QC5byJZw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<div id="demo">
<div class="flex justify-between flex-wrap">
  <div v-for="kink in kinks.data" :key="kink.id">
    <button type="button" @click="setBtn(kink.id)" :class="checkBtn(kink.id) ? 'bg-red-600' : 'bg-gray-600'" class=" m-1 my-2 inline-flex items-center px-3.5 py-2 border border-transparent text-sm leading-4 font-medium rounded-full shadow-sm text-white hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500"> {{ kink.name }}</button>
     </div>
</div>
</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

Material-Table does not allow resizing of columns if there are more than 5 columns present

I'm currently using the material-table library to present my data. Despite my attempts, setting a fixed size for each of my 19 columns isn't working as intended. Using width: 45% doesn't produce the expected visual result. Also, implementing ...

Fixing Cross-Browser Issues with the OnScroll Function

window.onscroll = function() { if( window.XMLHttpRequest ) { var bodyId=document.getElementById('bodymain'); if (bodyId.scrollTop > 187) { //make some div's position fixed } else { //mak ...

Validate the checkbox with Vuelidate only when the specified property is set to true

I have a website login form where users may need to check a specific checkbox before logging in. Here is part of the Vue component code that handles this functionality: <script setup lang="ts"> import {ref, defineProps} from 'vue&a ...

"Implementing classes with AngularJS: A Step-by-Step Guide

Is there a way to dynamically add a class to the i tag after a button is clicked in AngularJS? <button type="button" title="Like" ng-click="countLikes(product.title)" class="btn btn-compare"> <i class="fa fa-thumbs-o-up"></i> </ ...

Struggling with my `welcome.blade.php` not detecting Vue imported within my Nuxt.js directory

I have been working with Nuxt.js on my Laravel project. Combining them was a necessary step since they each come with their own boilerplate during installation into the project. I managed to make almost everything work smoothly until I encountered an issu ...

Unable to save the outcome in the session while using async waterfall

I have run a series of methods using async.waterfall which returns a result. I save this result in a request.session variable for later use with Ajax. However, I am facing an issue where I can set the value of the session variable initially but am unable t ...

Guide on integrating React.js into an HTML development webpage

I can't seem to get this code to work properly. I have saved it as an .html file on my computer, but it's not displaying anything when I try to open it in Google Chrome. <DOCTYPE! html> <html> <head> <script src= ...

Can a node.js file be exported with a class that includes IPC hooks?

[Node.js v8.10.0] To keep things simple, let's break down this example into three scripts: parent.js, first.js, and second.js parent.js: 'use strict'; const path = require('path'); const {fork} = require('child_process&apo ...

After using `setAttribute`, React is unable to produce any audio

Currently, I am facing an issue with a React component where it should play sound from an array of IDs stored in the database by setting the ID to the src attribute for the source tag. However, this functionality is not working as expected. Interestingly, ...

Updating the state across various components proves to be a challenge when relying on both the context API and higher order components

I have been working on updating the application state using the context API instead of using Redux, as I do not require all of its features and want to avoid prop drilling. With TypeScript, I created a global context and a higher-order component (HOC) wrap ...

Interactive Sidebar Navigation Content

On my website, I have a navigation sidebar that contains links to all of the main site pages. Each page has the same links, except the link to the current page is not included, making it easy to visually identify which page you are on. Currently, I manuall ...

What's causing my variables to be returned as null in the alerts?

Why am I receiving null values when alerting my variables? I'm attempting to pass a string stored in a variable from an external JavaScript file back to the main page using alerts. Initially, I suspected that the JavaScript was not fetching data cor ...

Implementing a Cancel Button in a Form Using Vue.js Bootstrap-Vue

I am trying to implement a cancel button in my code, similar to the reset button functionality, however, the method is not being triggered and the validation for required fields is still taking place. In my NewUser.vue file, I have added the @cancel="onCa ...

"Implementing a full page refresh when interacting with a map using

Here is an example of how I display a map on the entire page: <div id="map_canvas"> </div> UPDATE 2: I have successfully displayed a menu on the map, but there is a problem. When I click on the button, the menu appears briefly and then disapp ...

The web browser's engine is blocking the connection to the secure websocket server

Summary of Issue An error message stating "Websocket connection failed." appears in the browser console (Chrome or Brave) when trying to run this code: const ws = new WebSocket("wss://abcd.ngrok-free.app/") (Please note that the URL mentioned is not real ...

When using REACT to fetch data from an API, the absence of an 'Access-Control-Allow-Origin' header may result in access issues

I am working on a project that involves retrieving products from a company's API. After reaching out to the company, they provided me with the following information: CORS allowed origins for local development is "http://localhost:1229" To adhere t ...

struggling to update an array with user inputs on my to-do list app

I'm currently in the process of creating a small to-do list with some specific functionality. I want each text input (or a copy of it) to be added to an empty string, ensuring that the original input remains unchanged. The goal is to have a function t ...

Issue when attempting to animate an SVG point using translateX transformation

I am attempting to create a basic animation using the translate X property on a section of my svg when hovering over the element. Here is the code I have so far: <html> <style> .big-dot:hover { transform: translateX(20px); animat ...

jQuery Plugin - iDisplayLength Feature

I am currently using DataTables version 1.10.10 and I am looking to customize the main plugin Javascript in order to change the iDisplayLength value to -1. This adjustment will result in displaying "All" by default on all data tables, allowing users to fil ...

The modal window does not display a scroll bar

I'm currently facing an issue where the scroll bar is not appearing on my page when more elements are added. In addition, I have a modal that covers the entire page when clicking on an item. However, changing the CSS position: fixed property affects ...