Using Vue.js's computed property to dynamically bind a class in v-bind

I am familiar with using v-bind:class when returning true or false from a computed function.

I am curious to know if it is possible to use a computed property that matches the ID and value of a button being clicked. For example, clicking button 1 would allow me to retrieve its value and compare it with the data model bound to the input.

Currently, the button's value is synced to a Vue data property.

<label v-bind:class="myBtnClass">
        <input type="radio" name="button1" id="button1" value="1" v-model="valueOfBtn"> One 
</label>
<label v-bind:class="myBtnClass">
        <input type="radio" name="button2" id="button2" value="2" v-model="valueOfBtn"> Two 
</label>

new Vue({
    el: '#app',

    data: {
        'valueOfBtn': 1

Having this code snippet only work for one button is not ideal, as I do not want to repeat this block multiple times.

computed: {

myBtnClass: function () {
            var result = [];
            if (this.valueOfBtn == document.getElementById('button1').value)
            {
                result.push('primary');
            }
            return result;

Thank you in advance

Answer №1

It is recommended to utilize methods in this scenario:

export default = {
  methods: {

    customizeButtonClass: function(type) {
      var style = [];
      if (this.ofButtonType === type) {
        style.push('highlighted');
      }
      return style;
    },
  // ...
  }
}

Additionally, in the HTML code:

<label v-bind:class="customizeButtonClass('btn1')">
....
<label v-bind:class="customizeButtonClass('btn2')">

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

Create a mechanism in the API to ensure that only positive values greater than or equal to 0 are accepted

My goal is to process the API result and filter out any values less than 0. I've attempted to implement this feature, but so far without success: private handleChart(data: Object): void { const series = []; for (const [key, value] of Object.e ...

Morris.js tutorial: Enhancing bar charts with data labels

I have this: But I want this instead: Does morris.js support this feature? If not, what would be the most effective method to implement it? ...

Is Grouping Together Installed Private Modules Possible?

Exploring a modular JavaScript approach in my upcoming project is a new concept for me. I would prefer explanations to be simple due to my limited experience. I have uploaded my private package on npm: @name/package-name The private package contains mul ...

Installing external Javascript libraries on Parse cloud code can be done by following these steps

Currently, I have integrated these JavaScript libraries into my Parse cloud code. var request = require('request'); var fs = require('fs'); var Twit = require('twit'); However, the code refuses to compile if these libraries ...

Connecting with Node JS, utilising the power of Socket.IO, Express, and establishing

Hey everyone, I have an interesting concept that I'd like to discuss with you to get your thoughts on its feasibility. The idea is to set up an RFID reader connected to a MacMini (with the Mini hidden and only the RFID visible). An iPad would also be ...

Tips for avoiding parent div click interference in Angular

Working with Angular8, I have a div containing a routelink along with other components including a checkbox. Here's the structure: <div [routerLink]="['/somewhere', blablabla]"> <!--other components that navigate to the ro ...

streamlining form updates in vue

The code snippet provided is functional but unnecessarily complicated and lengthy. I am seeking a more efficient approach to achieve the desired outcome. <h6><label for="number">Change Number</label></h6> ...

Preventing jQuery parser from turning arrays into objects

My JavaScript data file has the following structure: data = { items : [ {name: 'ABC'}, {name: 'CDF'} ] } After passing this data to $.ajax(type: 'POST', data: data), the converted data appears like this: it ...

What is the best method for storing a model in a database?

Hello, I am currently attempting to save a model to the database. I am simply inputting the value of a title in order to save it, as my id is set to auto increment. However, I have encountered an issue where my attempts have been unsuccessful. Can someone ...

Activating two buttons in jquery will trigger this action

I am currently working on developing a filter button that will perform different actions based on which buttons are pressed. Pressing button1 will trigger one action, while pressing button2 will trigger another action. If button1 is pressed first, followe ...

Passing the index in React Native

I am currently developing a music app utilizing the react-native-track-player library. I have created three components named Clusters, Songlist, and Play. Understanding How the Screen Works The flow of components is as follows: Clusters component -> Song ...

Modify the style of a webpage through JavaScript

Need help with calling a JS event based on button presses and changing CSS font styling accordingly for each button? Check out the code snippet below: body { background-image: url("back2.jpg"); background-size: 100% 100%; } ...

Sending parameters to async.parallel in Node.js

My goal is to create a simple example that demonstrates the concept I have described. Below is my attempt at a minimal example, where I expect to see the following output: negative of 1 is -1 plus one of 2 is 3 Here is the code I've written: var asy ...

Having issues with creating a poll command for my Discord bot as it keeps throwing the error message: "Oops! TypeError: Cannot read property 'push' of undefined."

Can anyone assist me with my question? I am using discord v11.5.1 Below is the code: exports.run = async (bot, message) => { const options = [" ...

What is the method for implementing a global intercept for all tests in Cypress 6?

Exploring my Vue/Nuxt site, I aim to test every page with mocked API calls. To achieve this, the intercept() function (previously route() in older Cypress versions) is highly useful: Here's an example from homepage.spec.js: describe('home page&a ...

"What is the best way to eliminate duplicate data from an ng-repeat loop in AngularJS

I have a query regarding appending data from the second table into $scope.notiData in AngularJS. Additionally, I need to figure out how to remove ng-repeat data when the user clicks on the remove symbol X. I have attempted some code but it is not functioni ...

Using Vuetify's v-data-table to enable row click functionality

Currently, I am involved in a Vue project that utilizes Vuetify as our primary component library. We are using the v-data-table component to display information and redirecting to another view when a row is clicked, which is functioning correctly. During ...

Numerous JSON entities

Curious to know if it's achievable to load more than one JSON file with just a single jQuery.ajax() call. Or do I have to make separate calls for each file? Warm regards, Smccullough ...

Troubleshooting problems with dates in jQuery AJAX

Hey, I recently worked on formatting dates in jQuery Ajax. After fetching a date value from the database, I converted it to the format dd-MM-YYYY. However, there seems to be an issue where I'm receiving the previous month. For example, if the database ...

Interactive form found on a webpage

Hey there! I'm currently working on a task where I want a form to be displayed when the edit button is clicked. Once the save button in the form is pressed, I want to update my database with the new information. It's crucial that this process hap ...