What is the process for toggling a button using Vue.js?

Important Note: Implemented Vue.js and Vuetify.js for both functionality and styling.

Utilizing the :class and @click properties, I managed to alter the background color of a button to a specified color. However, this modification is being applied to all buttons, rather than just the one that was clicked on.

Query: How can I toggle a button individually without toggling all buttons at once?

Here is a snippet from my vue file:

<v-layout>
  <v-flex md6>
    <v-text-field>Welcome.</v-text-field>
  </v-flex md6>
  <v-flex id="icon-filter">
    <span>Filter by:</span>
    <v-btn class="filter-button" :class="{toggled: isToggled}" @click="isToggled = !isToggled"><v-icon>local_offer</v-icon></v-btn>
    <v-btn class="filter-button" :class="{toggled: isToggled}" @click="isToggled = !isToggled"><v-icon>notifications</v-icon></v-btn>
  </v-flex>
</v-layout>

In the script section of the same vue file:

<script>
  export default {
    data: function() {
      return {
        companies,
        msg: "indiv",
        dashboards: ['profile', 'charts'],
        isToggled: false
      }
    },
    methods: {
      
    }
  }
</script>

I have reviewed a similar question and received a Vue warning stating that the isToggled method is already defined as a data property. Toggle Class for an item Vue.js

Additionally, I have consulted the vue.js documentation regarding data binding, but still require assistance with this issue. https://v2.vuejs.org/v2/guide/class-and-style.html

Although the Vuetify framework offers toggled button components, the client prefers a unique style and thus those components cannot be utilized. https://vuetifyjs.com/components/buttons

Answer №1

Create a new vue file (named button.vue)...

button.vue

// template
<v-btn class="filter-button" :class="{toggled: isToggled}" @click="isToggled = !isToggled">
  <slot></slot>
</v-btn>

// script
export default {
  data: function () {
    return {
      isToggled: false
    }
  }
}

your_parent.vue

// script
import CustomButton from './button.vue'

export default {
  components: { CustomButton },
  data...
}

// template
<v-layout>
  <v-flex md6>
    <v-text-field>Welcome.</v-text-field>
  </v-flex md6>
  <v-flex id="icon-filter">
    <span>Filter by:</span>
    <custom-button><v-icon>local_offer</v-icon></custom-button>
    <custom-button><v-icon>notifications</v-icon></custom-button>
  </v-flex>
</v-layout>

Note: CustomButton and button.vue can be renamed as needed

This setup allows each custom-button to have its own toggleable data!

Answer №2

To implement this functionality, I suggest utilizing the @click event handler in combination with a custom function that accepts the $event parameter. Within this function, you can utilize JavaScript's classList.toggle method to dynamically apply a CSS class or use .toggle() for other actions.

@click="myToggleFunction($event)"

Next, define the method within your component:

methods: {
   myToggleFunction: function(event){
        let button = event.target;
        button.classList.toggle('toggled');
   }
}

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

How to use JavaScript regular expressions to extract the content following the second-to-last occurrence of a back

I currently have a regular expression that looks like this: /^.*[\\\/]/ At the moment, it removes every single backslash from a string. However, now I need to modify it in order to capture everything after the second to last backslash. Fo ...

I'm currently utilizing lint in my Angular 2+ project. Is there a way to arrange the constructor parameters in alphabetical order

I am struggling to organize the constructor parameters in TypeScript while using TSLINT with Angular9. I am looking for a rule similar to member-ordering that can help me sort them effectively. constructor( // Sort these private readonly router: R ...

Guide to customizing marker colors on APEXCHARTS in a Next.js project

Is there a way to specify the color of each data point individually? For example, something like { x: 'Yellow', y: [2100, 3000], colors: '#808080' }, as the default color is set for all markers under plotOptions > dumbbellColors. I n ...

Exploring the World of Github on Windows: Understanding the 'master' and 'gh-pages' Branches

I have developed a simple jQuery plugin and uploaded it to Github. I am using both the Github website and Github for Windows to manage this project. However, when I try to include the .js or .css files from Github using the Raw links, my browser fails due ...

jQuery and Ajax are facing a challenge in replacing HTML

Imagine a scenario where there is a button on a website that, when clicked, replaces a paragraph (<p>) with a header (<h1>). Unfortunately, the code to make this functionality work seems to be faulty: index.html <head> <script s ...

The dropdown menu is not able to retrieve information from the secondary database

I have been encountering multiple challenges while working on a web-based dynamic form that I am developing. My current major issue is with populating the second #bodytype dropdown based on the selection made in the first, #bodyman, dropdown. Subsequently ...

Tips for determining the width of an image and utilizing that measurement as the height in order to create a balanced square image

I am currently facing an issue with my code that is used to retrieve the width of an image which is set in percentages. Although I am able to obtain the width in pixels, I am struggling with correctly inserting the variable into the CSS property value usin ...

A Study on Particle Systems using THREE.js

While working on my particle System in THREE.js with SPARK.js, I have completed the necessary code for the system. However, I am facing an issue where nothing related to the Particle System is being displayed on the screen. Currently, I am trying to creat ...

Exporting Data Using Excel and a Javascript Table

Currently, I am utilizing angularjs to export data into excel from an uploaded table. Here is the code snippet I am using: function (e) {<br> window.open('data:application/vnd.ms-excel,' + encodeURIComponent($('div[id$=exporta ...

Validation for prototype malfunctioning

I am currently using Prototype.js to implement form validation on my website. One of the fields requires an ajax request to a PHP file for validation purposes. The PHP file will return '1' if the value is valid and '0' if it is not. Des ...

AngularJS utilizes JSON objects to store and manipulate data within

My task requires accessing information from an array that is nested inside another array in Json format. Here's a more detailed example: [ { "id": 1, "name": "PowerRanger", "description": "BLUE", "connections": [ {"id": 123,"meg ...

Passport.js does not provide authentication for server-side asynchronous requests

Recently, I configured Passport.js with the local-strategy on my express server. Interestingly, when I am logged in and send an asynchronous request within NextJS's getInitialProps, it allows the GET request through client-side rendering but not serv ...

Utilizing jQuery to Bind AJAX Events without a DOM Element

The documentation for jQuery AJAX Events provides examples that all involve using a jQuery DOM Element to declare a binding, like so: $('.log').ajaxSend( hander ); I am interested in capturing jQuery AJAX Events without the need for a DOM Eleme ...

Import a precise model from a glb file

Greetings! I am relatively new to working with ThreeJS and just getting the hang of it. After going through some tutorials, I have successfully managed to load glb files and render them in my browser with ease. Recently, I downloaded a GLB file from that ...

Locate the nearest index within the array

I'm currently working with an array of "events" where the key assigned to each event corresponds to the Unix Timestamp of that particular event. To illustrate, consider the following array of event objects in JS: var MyEventsArray=[]; MyEventsArray[1 ...

Is it typically required to install or declare anything in your frontend in order for CORS to be permitted?

I am currently facing a cross-origin error in my react/express project. The error message states: Error: A cross-origin error was thrown. React cannot access the actual error object during development. More information can be found at https://reactjs.org/l ...

Using the array.prototype.map method on props in React.js results in an array that is devoid

Recently, I've started exploring the world of React and encountered a problem while attempting to convert the value of props into a JSX element using array.prototype.map(). You can learn more about this method at this link. Here is a snippet of a Rea ...

How to place an element in a specific location within the DOM using JavaScript

How can I position a created element in a specific place within the DOM using this code? Currently, it appends at the bottom of the page. var x = document.getElementById('options_10528_1'); var pos = document.getElementById('options-10528- ...

Guideline on extracting private keys from Windows Certificate Manager

I am currently working in a Windows environment setting. Within my organization, we act as our own certificate authority for internally-used https applications. I have obtained a certificate from our system for a private web server I created. While using ...

Extracting Object Properties in JavaScript with React

Code: const [obj, setObj] = useState(() => ({ a: valueA, b: valueB, get values() { if (!this.a || !this.b) { return []; } // code... } return [this.a, this.b] }, })); Values update: useEf ...