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

Creating a dynamic image carousel using jQuery

Today, I completed the jQuery course on Code Academy and am now trying to create an image slider using it. While I have a general idea of how it should work, I feel like I'm missing a key element. My goal is to have the slider continuously running whe ...

Efficiency in Javascript coding techniques

Hey there, I'm seeking some feedback on the efficiency of my aspect ratio function. This function is designed to determine the aspect ratio and limit the size of an image. Take a look and let me know what you think! function constrainTwoNumbers(optio ...

Using a customized layout, merge AngularJS into Vaadin

I experimented with integrating an angular JS application into Vaadin by utilizing a custom layout as shown below: VerticalLayout mainLayout = new VerticalLayout(); mainLayout.setMargin(true); mainLayout.setWidth("1380px"); setCompositionRoot( ...

Guide on waiting for AWS assumeRole before proceeding with defining the module

I'm currently working on a module that needs to export functions and variables, but before it can do that, it must switch user roles. Here is the code snippet I've come up with. What I need is for the anonymous async function to execute first, an ...

Is there a way to transform a large gltf file into jsx format?

I recently created a 3D scene in Blender and wanted to incorporate it into my React Three Fiber project. However, after exporting the scene to glTF format, I discovered that the file contained around 300k lines. The strange thing is that the file works per ...

JavaScript is throwing an error stating that the requestData is undefined, even though the

Hello, I am attempting to retrieve weather information based on the country and city using the openweather api. JSON is a new concept for me in coding, so please bear with me through this learning process. Below is the code snippet that I have been workin ...

Using AngularJS to extract values from deeply nested JSON structures

I'm currently navigating through a nested JSON object and I'm facing challenges in accessing the sub items within it. Below is a snippet of the JSON file I'm working with. It has successfully passed the JSONLint test, so it should be in pro ...

Why does the CSHTML button containing a JavaScript onclick function only function intermittently?

I've implemented a download button on a webpage that dynamically assigns an ID based on the number of questions posted. Below is the code for the button: <input data-bind="attr: { id: $index() }" type="button" value="Downlo ...

What is the recommended sequence for adding AngularJS to the index page?

I am new to AngularJS and currently working on a project where I need to include multiple JavaScript files in my index.html page. After doing some research, I came across a post on Stack Overflow that mentioned the importance of including the angular.js fi ...

Is it possible to send two parameters to a JavaScript function using HTML?

Seeking help to develop an .html page where two string inputs are passed as parameters to a .js function, which then returns the longer of the two strings based on their lengths. Initially, I successfully created a functional .js script in VS CODE. Here i ...

Utilizing the "v-if" directive within a VueJS component

Can anyone provide a quick and simple solution? I need to display a "DEVELOPMENT" tag on my VueJS footer only when the NODE_ENV in .env is not set to "production". Any assistance would be greatly appreciated. <template> <footer class="app-foo ...

Tips for preserving the zoom level of flot charts during updates using AJAX

My application regularly queries the database for new data and updates a graph using Ajax. However, I am facing an issue where each time the graph is updated with new values, the current zoom level is reset. Is there a way to preserve the zoom position b ...

Tips for ensuring a document stays at the top of my collection when performing an update

Whenever I make changes to a document, it always ends up at the bottom of my collection. Is there a way to prevent this from happening? try { await Card.update({_id: fixedUrl}, {$push:{'comments': data}}) } catch (err) { console.log(err ...

I am encountering an issue with my Javascript file not running due to a bigint error

I'm attempting to utilize @metaplex/js for NFT minting. Usually, my .js files function correctly, but when I execute the file, this particular error arises. bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?) The meaning of ...

Animation of two divs stacked on top of each other

I am trying to replicate the animation seen on this website . I have two divs stacked on top of each other and I've written the following jQuery code: $('div.unternehmen-ahover').hover( function () { $('div.unternehmen-ahover' ...

Cutting an image in ReactJS using the HTML5 canvas feature

Seeking a way to crop images in reactjs without relying on any external library. The goal is for users to upload an image and perform cropping using raw JavaScript, then replace the uploaded image. How can this be achieved without the use of libraries? Loo ...

By default, make the initial element of the list the selected option in an AngularJS select input

I'm running into an issue with setting the first element in my ng-repeat list within a select input. Here is the code snippet causing the problem: <div> <span >OF</span> <select ng-model="eclatementCourante.ordreFabricationId" n ...

Adjust Camera Position in A-Frame Scene Based on Scrolling Movement

I've been struggling to find a solution for this particular scenario in Aframe. I want to create an embedded Aframe scene as the background of a webpage and have the camera move along a path as the user scrolls down the page. I've set up a scene ...

Encountering a tucked-away issue with the Safari scroll bar?

Encountered an interesting bug where users are unable to scroll down a text nested inside a div. This issue seems to be isolated to Safari, as it doesn't occur in other browsers. I have prepared a sample file to demonstrate the bug and would apprecia ...

Executing both JavaScript Promise .then() and .catch concurrently

I've been working on converting my WordPress comments into an ajax-driven system. Everything was going smoothly until I encountered a problem with the .catch() method triggering right after the .then() method. Below is the code snippet... Ajax engi ...