Utilizing the correct method for binding checkboxes in Vue JS for effective two-way communication

I am working with data retrieved from a MySQL database where "1" and "0" represent boolean true and false. In my Vue component, I have set these values as shown below:

    data(){
    return {
    form : {
         attribute_1 : "1", //attribute 1 is true
         attribute_2 : "0", //attribute 2 is false
         attribute_3 : "1", //attribute 3 is true
          }
        }
       }

To maintain two-way binding, I have implemented computed properties like this:

 attribute1: {
            get(){
                return this.form.attribute_1 == "1" ? true : false ;
            },
            set(newValue){
                this.form.attribute_1 = newValue ? "1" : "0";
            }
        },
 attribute2: {
            get(){
                return this.form.attribute_2 == "1" ? true : false ;
            },
            set(newValue){
                this.form.attribute_2 = newValue ? "1" : "0";
            }
        }, ...

These computed properties are used in the HTML code like so:

<input type="checkbox"  checked v-model="attribute1">
<input type="checkbox"  checked v-model="attribute2">

While this approach works well for achieving two-way binding in Vue, it does result in repetitive code.

Another potential method involves using the @change event to monitor checkbox changes, but this seems to offer only one-way binding. The Vue console shows updated values only upon panel refresh.

Are there any better techniques for implementing two-way binding in this specific scenario?

Answer №1

To update your template to achieve this, follow these steps:

<input type="checkbox" v-model="form.attribute1" :true-value="1" :false-value="0">
<input type="checkbox" v-model="form.attribute2" :true-value="1" :false-value="0">

With these changes, you won't need any computed properties anymore. The value of this.form.attribute1 will be "1" when the checkbox is checked and "0" when unchecked. Additionally, if you set form.attribute1 as "1", then the checkbox will be checked by default, as demonstrated below.

DEMO:

new Vue({
  el: '#app',
  data(){
    return {
      form: {
        attribute1: "1", //attribute 1 is true
        attribute2: "0"  //attribute 2 is false
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <input type="checkbox" v-model="form.attribute1" :true-value="1" :false-value="0">
  <label for="checkbox">{{ form.attribute1 }}</label><br/><br/>
  <input type="checkbox" v-model="form.attribute2" :true-value="1" :false-value="0">
  <label for="checkbox">{{ form.attribute2 }}</label><br/><br/>
</div>

Answer №2

One approach I really like is creating a custom component for this purpose. Let's take a look at My Checkbox.vue component:

<template>
    <input type="checkbox" :checked="isChecked" @change="handleChange" />
</template>

<script>
export default {
    props: {
        value: {}
    },
    computed: {
        isChecked() {
            return this.value === "1" || this.value === true;
        }
    },
    methods: {
        handleChange(event) {
            this.$emit("input", event.target.checked ? "1" : "0");
        }
    }
};
</script>

You can use this component in other components like this:

<template>
    <div>
        <Checkbox v-model="isChecked" />
    </div>
</template>

<script>
import Checkbox from "./Checkbox";
export default {
    components: {
        Checkbox
    },
    data() {
        return {
            isChecked: "1"
        }
    }
};
</script>

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

The Mysteries of Key Codes in JavaScript

I'm curious about the character codes used for keyboards. Recently, I came across an informative article discussing this topic. In particular, I am interested in finding out which key code to use when a user presses both the alt and down arrow keys s ...

Is there an easy way to determine if an element inside a Vue component is overflowing?

I created a unique component called ResultPill which includes a tooltip feature (implemented using vuikit). The text displayed in the tooltip is determined by a getter function called tooltip, utilizing vue-property-decorator. Here are the relevant parts o ...

What is the process of integrating ES6 modules with app.get in a Node/Express routing application?

After researching the benefits of ES6 export, I made the decision to implement it in a NodeJS/Express project instead of using module exports. The MDN documentation explained that export is used as shown below: export function draw(ctx, length, x, y, color ...

What is the reason for my Firestore listener consistently retrieving data from the server despite having offline persistence enabled?

Incorporating Firebase JavaScript Modular Web Version 9 SDK into my Vue 3 / TypeScript application. My understanding is that when utilizing real-time listeners with offline persistence in Firestore, the process should proceed as follows: Upon initializat ...

Reactive map not triggering Vue computed() function

Having a reactive relationship with an initially empty map: const map = reactive({});, I also have a computed property that checks if the map contains a key named "key": const mapContainsKeyComputed = computed(() => map.hasOwnProperty("key")). However, ...

JavaScript code to find a date within a specified range

I have developed a script that calculates the number of weeks between two specified dates. It then generates a table where the number of rows equals the number of weeks. The script can be viewed on JSFIDDLE Script: $('#test').click(function ...

"Using JavaScript to trigger a button click event, and then

I have a question that I think may sound silly, but here it is. I have this code snippet: <script type="text/javascript"> $(document).ready(function(){ var email_value = prompt('Please enter your email address'); if(email_value !== null){ ...

Verify if the user is currently inputting text within a specific range of characters within

I am dealing with a specific issue involving a textarea. By default, this textarea contains a string of any type, but a user is only able to type inside opening and closing brackets. For example, "Leave[]" allows typing within the brackets but not outsid ...

Even when there is a change in value within the beforeEach hook, the original value remains unchanged and is used for dynamic tests

My current project setup: I am currently conducting dynamic tests on cypress where I receive a list of names from environment variables. The number of tests I run depends on the number of names in this list. What I aim to achieve: My main goal is to manip ...

Is there a way to display shortened text only when hovering without altering the height of the list box?

Here is my script for a vue component : <template> ... <b-card-group deck v-for="row in formattedClubs"> <b-card v-for="club in row" img-src="http://placehold.it/130?text=No-image" img-alt="Img ...

How can I prevent my code from resetting every time a state update occurs?

https://i.sstatic.net/snSGl.pngI've coded a program that creates a 10x10 grid with 5 boxes of varying sizes. When you click on a box, an x is added to its content and the turn state is set to false. The issue arises when the code re-runs after each s ...

Unable to submit /api/sentiment

I'm currently troubleshooting the /api/sentiment endpoint in postman and encountering a "cannot POST" error. I have confirmed that the routes are correct and the server is actively listening on port 8080. Interestingly, all other endpoints function wi ...

Issues with Javascript functionality on aspdotnetstorefront site

Lately, I've been facing some challenges with my Javascript and jQuery codes when trying to implement them in the storefront. Despite attempting different methods to create a slider, none seem to work within the store environment - even though they fu ...

I am facing an issue where both curl and file_get_contents are not functioning properly after

When attempting to access a user's city information using coordinates, I have encountered an issue with the response not being displayed in my console. The process involves a javascript function that takes latitude and longitude data, sends it to a PH ...

Show the chosen item from a dropdown menu using Bootstrap

Here is the HTML code that I am working with: <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="h ...

The error message "MediaMetadata is not defined as no-undef and cannot be used as a constructor" appeared when trying to use MediaMetadata

I have successfully implemented a playlist player using howler.js in vuejs. Now, I am looking to enhance it by integrating the MediaMetadata API. While the MediaSession API is functioning well with controls like notification bar, keyboard controls, and rem ...

Leveraging Next.js 'useClient' in conjunction with server component (global)

Hello there! I'm trying to achieve a 50% opacity effect on my Gallery when the search bar is in use. However, I'm facing challenges using 'use client' with the glob library. Here's the code snippet: app/page.tsx "use client&qu ...

Using Parseint in a Vue.js method

For instance, let's say this.last is 5 and this.current is 60. I want the sum of this.last + this.current to be 65, not 605. I attempted using parseInt(this.last + this.current) but it did not work as expected. <button class="plus" @click="plus"&g ...

Unable to retrieve information from JSON file utilizing AngularJS version 1.6

I'm having trouble retrieving data from my JSON file using AngularJs 1.6 myApp.controller("homeCtrl", function($scope, $http) { $scope.Data = []; var getJsonData = function() { $http.get('contactlist.json').then(func ...

Ways to adjust the position of a DIV based on its index value

I'm currently working on a unique project that involves creating a triangular grid using HTML and CSS. The challenge I am facing is offsetting each triangle in the grid to the left by increasing amounts so they fit seamlessly next to one another. Righ ...