Vue3 is struggling to apply dynamic styling exclusively to certain buttons

Currently, I am diving into the world of vue and facing a challenge in styling buttons dynamically when clicked individually. These buttons serve as filters for a list of products, and my goal is to apply one style when the filter is 'on' and another when it is 'off'. While I have succeeded in updating styles dynamically, the issue lies in all buttons changing their style upon any single click. On the bright side, the actual filtering function works perfectly (the products are properly filtered out upon clicking the respective button).

In the code snippet provided, the mode is passed to the BaseButton component, where it is applied as the class.

<template>
    <ul>
        <li v-for="genus of genusList" :key="genus.label">
            <BaseButton @click="filterGenus(genus.label)"  :mode="genusClicked.clicked ? 'outline' :''">
                {{ genus.label }}
            </BaseButton>
        </li>
        <BaseButton @click="clearFilter()" mode="flat">Clear Filter</BaseButton>
    </ul>
    </template>


    methods: {
        filterGenus(selectedGenus) {
            this.clickedGenus = selectedGenus
            this.clicked = !this.clicked
            this.$emit('filter-genus', selectedGenus)
        },
        clearFilter() {
            this.$emit('clear-filter')
        }
    },

I attempted creating a computed value to add a .clicked property to the genusList object, but unfortunately, it did not provide a solution to the problem.

Answer №1

If you want multiple buttons styled at once, consider saving them in an array. For a single button, just save it individually:

const app = Vue.createApp({
  data() {
    return {
      genusList: [{label: 1}, {label: 2}, {label: 3}],
      selGenus: [],
    };
  },
  methods: {
    isSelected(selectedGenus) {
      return this.selGenus.includes(selectedGenus)
    },
    filterGenus(selectedGenus) {
      if (this.isSelected(selectedGenus)) {
        this.selGenus = this.selGenus.filter(s => s !== selectedGenus)
      } else {
        this.selGenus = [...this.selGenus, selectedGenus]
      }
      this.$emit('filter-genus', selectedGenus)
    },
    clearFilter() {
      this.selGenus = []
      this.$emit('clear-filter')
    }
  },
})
app.component('baseButton', {
  template: `<button :class="mode"><slot /></button>`,
  props: ['mode']
})
app.mount('#demo')
.outline {
  outline: 2px solid red;
}
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <ul>
    <li v-for="genus of genusList" :key="genus.label">
      <base-button @click="filterGenus(genus.label)" 
                   :mode="isSelected(genus.label) ? 'outline' :''">
        {{ genus.label }}
      </base-button>
    </li>
    <base-button @click="clearFilter()" mode="flat">
      Clear Filter
    </base-button>
  </ul>
</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

Evaluate the functionality of an Angular controller method that interacts with the Document Object Model (

We currently have an AngularJS controller that contains the following function: $scope.testMe = function() { return $('#test'); } So, how can we effectively test this function? We attempted a Karma test as shown below: describe(' ...

Struggling with passing the decoded user ID from Node Express() middleware to a route can be problematic

I have encountered a similar issue to one previously asked on Stack Overflow (NodeJS Express Router, pass decoded object between middleware and route?). In my scenario, I am using the VerifyOrdinaryUser function as middleware in the favorites.js route. Th ...

Tips for initiating a component within a loop and terminating it after completing all 3 iterations

Looking for a solution to open and close tags in a loop every 3 iterations. The objective is to create a grid using container, row, and column elements. However, I am unsure how to achieve this. Example: render(){ const arrayName = ["john", " ...

Using directive to access service values directly

I am in need of utilizing a directive to fetch and display data using ng-repeat from a service. The anticipated result will be <ul>Days <li>Monday</li> <li>Tuesday</li> ... <ul> <ul>Month <li>January</li ...

Optimizing Angular.js templates for faster loading using Node.js pre-compilation

As I delve into learning Angular and integrating it with my current Node.js framework, I find myself facing some challenges. Previously, I utilized Handlebars.js as my templating engine in Node.js, where I would build the context on the server side and the ...

Connect the input field to the grid component

How can I sync the value of the SearchFilter with the FilterGrid to effectively filter the data (refer to code below)? I'm facing an issue where the field clears out the value as I type. There seems to be a problem in how I'm utilizing the state ...

Passing parameters to an Angular 2 component

When it comes to passing a string parameter to my component, I need the flexibility to adjust the parameters of services based on the passed value. Here's how I handle it: In my index.html, I simply call my component and pass the required parameter. ...

Error encountered: Application module "MyApp" not found

I have set up AngularJs and jQuery using RequireJs within a nodeJs framework. This is my main.js setup require.config({ paths: { angular: 'vendor/angular.min', bootstrap: 'vendor/twitter/bootstrap', jqu ...

Post-installation of NPM, configuring CA certificates on Windows system

TLDR; Is there a way to seamlessly set NODE_EXTRA_CA_CERTS in a Windows environment for NPM packages' post-install scripts without requiring system changes, configuration file modifications, or admin-level permissions? Details This issue has been f ...

Inform the PHP backend that the browser has been closed by the frontend Angular application

Currently, I am working on an Angular project that is interacting with a backend project created using PHP and ZF3. I am trying to figure out the most efficient method of informing the backend project when the user closes the browser window. Initially, I ...

JavaScript is having trouble locating the HTML select element

Having trouble selecting the HTML select element with JavaScript? You're not alone. Despite trying different solutions found online, like waiting for the window to fully load: window.onload = function(){ var opt = document.getElementsByName("prod ...

What are the steps to making a textfield editable with JavaScript and HTML?

My textfield is currently populated with values from the database and is functioning perfectly. I would like to implement a checkbox feature that, when clicked, will clear the textfield of the database values, allowing the user to input new values. If t ...

Adding a JavaScript script tag within a React app's ComponentDidMount - a guide

I am currently in the process of implementing Google Optimize on my website. I need to include the following script tag within my page: <script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date; h.end=i=function(){s.classN ...

What is the best way to retrieve dynamic content from a .txt file and have it displayed on multiple HTML pages as they are loaded dynamically?

I have a file named 'm_data.txt' stored on the server that contains a continuous total of 77 (for instance). The total gets updated via a push.php page that writes to the .txt file. <!DOCTYPE html> <html> <head> <title> ...

Despite having unique ids, two file input forms are displayed in the same div in the image preview

Running into a minor issue once again. It may not be the most eloquent query, but I'm genuinely stuck and in need of some assistance. I am attempting to showcase image previews of selected files in a file input form. I have a jQuery script that reads ...

When using Vue.js and Quasar to implement multiple filtering forms, an issue arises where the input value disappears

I am currently exploring how to implement multi-item filtering in Quasar, a framework of Vue. At the moment, I am utilizing input and checkbox elements. Everything seems to be functioning correctly, but there is an issue with the select item disappearing. ...

The functionality of changing the checkbox to "checked" by clicking on the span is not

How can I create a toggle button with a checkbox using css and jquery? Clicking on the span representing the toggle button should change the checked property of the checkbox. Currently, the span does not change the property, even though it triggers the c ...

Generating a dynamic sitemap with Next.js

I have been working on a project where I need to create a sitemap, and I am currently using next-sitemap for generation. However, I've encountered an issue with this method, as well as other solutions I've come across, because the sitemap is only ...

Infinite scrolling made effortless with jQuery and Ajax

I am attempting to create a basic infinite scroll feature that monitors when the user scrolls to the bottom in an HTML file. Once the bottom is reached, it should then load additional content from another HTML file which contains more text. The second HTM ...

Effectively detect the 'scrollend' event on mobile devices

When implementing the -webkit-overflow-scrolling: touch; style on a mobile element, dealing with scroll events can be quite challenging as they are triggered by various actions such as 'flicking', 'panning' and when the scroll comes to ...