Steering Vue with Vuetify to output checked value

What's the correct method to pass the 'checked' value from a child component to its parent?

I have a checkbox nested within a component that utilizes v-checkbox from Vuetify. I want to send the checked value to its parent component. Currently, I am achieving this by emitting $event and it works correctly as $emit includes the true/false value. However, I am puzzled as I expected to emit $event.target.checked but this returns undefined.

Checkbox.vue

<template>
  <v-checkbox color="primaryGreen" hide-details @change="$emit('change', $event)">
    <span slot="label" class="checkbox-label">
      <slot></slot>
    </span>
  </v-checkbox>
</template>

Form.vue (parent)

<v-layout id="different-address-checkbox">
  <v-flex>
   <checkbox @change="updateAddress">
    <span>Different Address</span>
   </checkbox>
  </v-flex>
</v-layout>

export default {
  data() {
    return {
      differentAddress: false
    };
  },
  methods: {
    updateAddress(value) {
      this.differentAddress = value;
    }
  }
};

I am uncertain why $emit provides true/false instead of the entire event with event.target.checked, and I am unsure of the correct approach to emit the checked value from child to parent.

Answer №1

v-checkbox is a custom form element in the Vuetify framework, emitting a boolean value as determined by the framework's developer.

While traditional form elements require accessing values with $event.target.checked or $event.target.value, custom components like v-checkbox handle value changes differently.

The source code snippet in Vuetify's source shows how the internalValue property is updated and emits events to the parent component.

internalValue: {
    get () {
      return this.lazyValue
    },
    set (val) {
      this.lazyValue = val
      this.$emit(this.$_modelEvent, val)
    }
},

Changes in the component's value trigger the emission of the internalValue to the parent component.

Answer №2

Relocate

@method="$emit('method', $event)

into a property of the method

Answer №3

I encountered a similar issue with a complex data model and nested for-loops. I needed a simple way to retrieve the v-checkbox with a changed checked state.

Here is the solution I came up with:

<div v-for="unitLocation in groupedResources" v-bind:key="unitLocation.node.TelldusUnitLocation_Name">

    <v-checkbox
        @change="toggledLocation(unitLocation)"
        v-model="unitLocation.node.checked"
        :label="unitLocation.node.TelldusUnitLocation_Name"
        hide-details
    ></v-checkbox>

    <!-- additional code goes here -->
</div>

(unitLocation is a nested object with properties node and children, but these details are not relevant for the solution)

Subsequently, in my code:

methods: { 
  toggledLocation(args) {
    debugger; /*refer to the image below for the console log in Chrome*/
  }
}

Here is the output in Chrome (the parameter args was printed out in the debug console): https://i.sstatic.net/xVTP3.png

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

What is the best way to display items using Typeahead.js in combination with the Bloodhound engine?

I am struggling to showcase a collection of items using typeahead with a JSON file as the data source. Unfortunately, none of my information is appearing on the screen. My objective is to list the names and utilize the other attributes for different purpo ...

Exploring the internet with Internet Explorer is like navigating a jungle of if statements

I am facing an issue with my code that works well in Chrome, but encounters errors in IE. The if condition functions correctly in Chrome, however, in IE it seems like the first condition always gets executed despite the value of resData. Upon analysis thro ...

Creating a mesmerizing glass effect in Three.js using a PNG image mask on a video texture

The other day, I revisited activetheory.net and was captivated by the beautiful glass effect on the Homescreen logo border. I tried to replicate it by examining the minified code and discovered they were using a PNG as a mask. I successfully loaded a PNG ...

Count duplicated values in an array of objects using JavaScript ES6

I am working on creating a filter for my list of products to count all producers and display them as follows: Apple (3) I have managed to eliminate duplicates from the array: ["Apple", "Apple", "Apple"] using this helpful link: Get all non-unique values ...

Tips for shutting down a modal box without using the "x" button?

I'm currently working on creating a modal box using HTML and Javascript, and I came across this example (reference https://www.w3schools.com/howto/howto_css_modals.asp), which seems to fit my needs quite well... I made some modifications to it... &l ...

"Executing the ajax send() function does not result in any changes to the

Just starting to explore ajax and I need some help. Can anyone explain why the address bar is not updating when using ajax send()? The connection is working, but it keeps displaying "There is no variable!" PS: Please note that I prefer not to use JQuery. ...

Tips for bundling a Vue Single File component using Vite for secure loading over HTTPS

I am in the process of compiling and packaging my Vue Single File component for distribution and dynamic loading via HTTP. After stumbling upon Markus Oberlehner's insightful article, I learned about using Vue CLI v3 with the command below: npx vue-c ...

Calculate the sum of the products when multiplying two values from every array of objects, using Reactjs/Javascript

I'm currently developing an eCommerce application and need to calculate the total price of items that users have ordered. I have an array named 'orders' which contains all the ordered items, each item has two keys - payablePrice and purchase ...

Ways to enhance background removal in OpenCV using two images

I am currently using OpenCV in conjunction with NodeJS (opencv4nodejs), and I am working on a project that involves replacing the background of webcam images. I have one image with a person's head in the frame, and another without. My code is functio ...

Having trouble accessing properties that are undefined while using react JS, specifically when trying to read a 'map' property

Currently, I am in the process of building a blog with ReactJS and NextJS within VS Code. Despite not encountering any errors during coding, when I attempt to run it, the browser displays: "TypeError: Cannot read properties of undefined (reading 'map& ...

React and Material UI: Ensuring Proper Whitespace Handling in Strings

Exploring the use of Typography component from Material UI (https://material-ui.com/api/typography/) The main objective is to maintain the new lines and spaces in a saved string. For instance, if the string contains leading spaces and new lines, it shoul ...

Change the syntax to use async-await

Is it worth converting the syntax to async-await and how can I achieve this? // ---- UserRoutes ---- router.get('/user', middlewareJwt.jwtHandler, function (req, res) { UserService.get(req.userId, (user) => successCbk(res, 200, { ...

Looking to reset the default display option in a select dropdown using JavaScript or jQuery?

Here is some HTML code for a select element: <select> <br> <option>1</option><br> <option>2</option><br> </select> This select element will initially display the first option item (display ...

The variable is only recognized within the function and not outside of it

Seeking assistance as a newcomer in debugging and implementing code, I have been trying various approaches to pass a base64string into JotForms for generating images in PDF format. Below is the screenshot of the error encountered. View error here The foll ...

MUI: The value you have chosen for the select component is outside the acceptable range - `[object Object]`

I'm currently in the process of developing a custom Select component that offers both single and multi-selection features. Below is how I initialize the components: const vendorList = [ { label: "John", value: "668", } ...

Tips for using jQuery dropdown menus

I am currently in the process of creating a prototype for a quick dropdown menu using jQuery. However, I have reached the limits of my knowledge on jQuery and could use some assistance in solving my issue. My objective is to have a dropdown animate down w ...

JSON.stringify not behaving as anticipated

I am working on the code below; var data = []; data['id'] = 105; data['authenticated'] = true; console.log(data); var jsonData = JSON.stringify(data); console.log(jsonData); The initial console.log is displaying; [id: 105, authenti ...

How to remove a loop-rendered component from the DOM in Vue

My website has an image upload form where users can select multiple images. Once the images are selected, they are previewed and users can provide meta info such as Category and Type for each image. This functionality is implemented in the upload.vue file ...

Generate and display a random element on a webpage using Javascript or jQuery on page refresh

Currently, I am developing a website for my unique custom themes on a blogging platform. One of the features I am looking to add is a review section, where only one random review will display per page refresh. My question is, can anyone assist me in crea ...

Choosing an element beneath a table row using a different element as a reference

I'm attempting to identify the checkboxes associated with the link containing delete.jpg. Here's what I've tried so far: <table> <tr class="odd"> <td><input id="cbox1" type="checkbox"></input></td> ...