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

Incorporate a minimum height requirement for enabling the scroll to top feature

I am currently dealing with some JavaScript code that scrolls to a specific div when clicked. However, I have encountered an issue where the div is displayed at the very top of the page, causing it to go behind a fixed header that is 90px in height. As a r ...

Set a delay for an AJAX request using jQuery

Is it possible to incorporate a setTimeout function into this ajax call? Here's the code snippet: jQuery.ajax({ type : "POST", url : dir+"all/money/myFile.php", data : "page="+data.replace(/\&/g, '^'), suc ...

Fixing the "Module not found" error in an Angular library using npm link

I'm currently working on creating an Angular wrapper for a Javascript library, but I've encountered a "Module not found" error. The Javascript library is still in development and has not been published to NPM yet. To work around this issue, I hav ...

Adjust the width of your table content to perfectly fit within the designated width by utilizing the CSS property "table width:

Example of a table <table> <tr> <td>Name</td> <td>John</td> <td>Age</td> <td>25</td> <td>Job Title</td> <td>Software Engineer ...

Why is my VueJS 2.0 deployment to a sub-folder resulting in a blank page?

I've been attempting to launch my Vue2 web application in a subdirectory on my domain, but I'm encountering a blank page. I've experimented with various solutions like adjusting the config/index.js file to correspond with the path on my live ...

How can I implement the dynamic loading of components using the Vue 3 composition API?

My goal is to dynamically load a component with the name retrieved from the database, however, I keep encountering the error [Vue warn]: Component is missing template or render function. import SimpleQuestions from '@/components/SimpleQuestions.vue&ap ...

Populating a HTML document with data retrieved from an AJAX request

I have a button that, when clicked, should display the values of a specific user. The code snippet for this functionality is as follows: HTML Button: <button onclick="return getUserDetails(<? echo $user['id']; ?>)" class="btn btn-xs bt ...

PHP script encountering difficulty inserting data into database when AJAX is utilized; functions flawlessly without AJAX

In my "user registration" file, there is a form with the following structure: <form action="" method="POST"> <label for="user" class="control-label">User </label> <input type="text" name="user" class="form-control" id="user" ...

What is the best way to incorporate server-side rendered content from a CMS to hydrate Vue.js?

Consider this scenario: content is managed through a traditional CMS such as Joomla or Drupal content is provided by the CMS as fully rendered HTML and CSS In the Frontend React.js should be utilized for all UI interactions. Despite going over most of R ...

Populate a database with information collected from a dynamic form submission

I recently created a dynamic form where users can add multiple fields as needed. However, I'm facing a challenge when it comes to saving this data into the database. You can view a similar code snippet for my form here. <form id="addFields" me ...

What causes req.body to be null after using event.preventDefault() in conjunction with fetch api, express, and node.js?

Is there a way to submit a form without causing the page to reload and still retrieve an object from MongoDB using server side scripts? I've tried preventing the default behavior of the form with an event handler to avoid the page refresh, but this ca ...

Modifying the data attribute within the div does not result in a different image for the 360-degree spin view

My current project involves utilizing js-cloudimage-360-view.min.js to create a 360-degree view of images. I have successfully retrieved the images, but I am encountering difficulty in updating the images by clicking a button. index.html <!DOCTYPE html ...

You can activate the ability to click on the main tag by setting routerlink as the child component in Vue

Within my HTML code, I have utilized a RouterLink within an li tag to create a basic dropdown menu. Currently, when options are displayed in the dropdown menu, I am only able to click on the text itself to navigate to the next page. However, I would like t ...

Tips on arranging JSON elements based on the sequence of another JSON

Currently, I am facing a challenge with sorting a list of parks (park_list) based on both distance and area. The code snippet below successfully sorts the list by distance: sortList(index){ return function(a, b){ return (a[index] === b[index] ? 0 : ...

No content appearing instead of AngularJS code displayed

My goal is to retrieve data from a MySQL database using PHP and then pass that data in JSON format to AngularJS for display in a table. The HTML code looks like this: <body ng-app="myModule"> <div class="row"> <div class="col-lg-12 ...

Is it possible to achieve a fade effect in material-ui that truly hides the component instead of just disabling its visibility? If so, how can this be accomplished?

Currently, I am utilizing the component provided by material-ui, which can be found at material-ui. <Fade in={!randomizeFlag}> <Grid> <FormControlLabel control={<Switch onChange={this.handleStartValueFlag} & ...

"What exactly does {...props} refer to and what is the best way to obtain my function from another

Currently, I am focusing on learning react native with a specific interest in react navigation v5. As mentioned in this resource: https://reactnavigation.org/docs/themes/#using-the-current-theme-in-your-own-components, my goal is to implement a dark mode ...

Inexplicably, HighCharts flips its axis when exporting data

I am facing an issue with the display of my Highchart in the web application. While it appears correctly in the browser, the exported chart flips the axis and shows a different image. Below are the options I have configured for my Highchart: var options = ...

Modify the event from creating a table on click to loading it on the page onload

Hey there, friends! I've been brainstorming and came up with an idea, but now I'm stuck trying to switch the code to onload(). I've tried numerous approaches, but none seem to be working for me. Below is the code I've been working wit ...

Struggling outcomes in Vue version 2.6

Consider this: <table class="v-gridView" style="width:100%;"> <template v-for="(row, idx) in rows"> <tr :key="row.key" :class="rowCla ...