send the checkbox control's model value back to the parent control in Vue3

I've implemented a wrapper control for checkboxes that closely resembles my textbox control. This approach ensures consistent validation and design throughout the application. While I was successful in getting it to work for textboxes, I encountered some challenges with the boolean value for the "checked" property.

Two way binding of data between child and parent using emit vue3 typescript

<template>
  <label class="checkCtrl">
    <input
      role="checkbox"
      aria-disabled="false"
      aria-readonly="false"
      type="checkbox"
      v-model="checked"
      v-on:change="change($event)"
    />
    <span><LocCtrl :page="page" :loc-key="labelLoc" /></span>
  </label>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useModelWrapper } from "../utils/modelWrapper";
import LocCtrl from "../components/LocCtrl.vue";
import Locale from "@/services/Locale";

export default defineComponent({
  name: "CheckCtrl",
  components: {
    LocCtrl,
  },
  props: {
    labelLoc: {
      type: String,
      required: true,
    },
    modelValue: {
      type: String,
      required: true,
    },
    page: {
      type: String,
      required: true,
    }
  },
  setup(props, { emit }) {

    const value = useModelWrapper(props, emit, "value");
    return {
      value: value,
      checked: value.value == "true"
    }
  },
  methods: {
    getLoc(locKey: string): string {
      return Locale.getItem(this.page, locKey);
    },
    change(e: Event): void {
     if (e) {
        this.value = (e.target as HTMLInputElement).checked ? "true" : "false";
        this.$emit('update:modelValue',  this.value);
        alert(this.value);
      }
    }
  },
});
</script>

This is the model wrapper that worked for textboxes but ran into issues with checkboxes

import { computed } from "vue";
export function useModelWrapper(
  props: { [x: string]: any },
  emit: (arg0: string, arg1: any) => void,
  name = "modelValue"
) {
 return computed({
    get: () => {
      return props[name];
    },
    set: (value: string) => {
      return emit("update:" + name, value)
    }
  });
}

In the parent component, I'm passing the v-model to the checkbox control. The expected values are strings "true" or "false" (which can be easily configurable if needed).

<FormLine className="forCheck" form-line="3">
    <CheckCtrl v-model="claim.resultOfAccident" labelLoc="RoA" page="claims3View"/>
</FormLine>

Answer №1

Once again, I managed to find a solution to my problem on my own. Hopefully, this code snippet can be beneficial to others:

onChange(event: Event): void {
   if (event) {
      const result = (event.target as HTMLInputElement).checked ? "true" : "false";
      this.$emit('update:modelValue', result);
   }
}

The initial issue with 'this.value' has now been resolved.

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

Exploring TypeScript and React Hooks for managing state and handling events

What are the different types of React.js's state and events? In the code snippet provided, I am currently using type: any as a workaround, but it feels like a hack. How can I properly define the types for them? When defining my custom hooks: If I u ...

Yup will throw an error if both a minimum value is set and the field is also marked

I am attempting to validate my schema using yup: import * as yup from "yup"; let schema = yup.object().shape({ name: yup.string().min(5) }); const x = { name: "" }; // Check validity schema .validate(x, { abortEarly: false }) . ...

What is the best way to pause function execution until a user action is completed within a separate Modal?

I'm currently working on a drink tracking application. Users have the ability to add drinks, but there is also a drink limit feature in place to alert them when they reach their set limit. A modal will pop up with options to cancel or continue adding ...

There is no way to convert a strongly typed object into an observable object using MobX

I have been utilizing the MobX library in conjunction with ReactJS, and it has integrated quite smoothly. Currently, I am working with an observable array structured as follows: @observable items = []; When I add an object in the following manner, everyt ...

Validate object containing both static and dynamic keys

I'm attempting to create a Yup validation schema for an object with the following structure: interface myObject { prop0: Date prop1: { nestedProp1: string nestedProp2: number [key: string]: string | number } } This is what I have tr ...

Guide on Executing a Callback Function Once an Asynchronous For Loop Completes

Is there a way to trigger a callback function in the scan function after the for await loop completes? let personObj = {}; let personArray = []; async function scan() { for await (const person of mapper.scan({valueConstructor: Person})) { ...

How can I retrieve the /api/auth/me resource serverside using the NextJS AppRouter?

I am looking to implement app router in my Next.js project and have encountered an issue. In order for my app to function properly, I need to make a call to /api/auth/me which will return either a user object or null if the user is not logged in. To achiev ...

Handling JSON data with Reactive Extensions in JavaScript

Hey everyone, I'm a beginner in Angular and RxJS coming from a background in VueJS. I've been struggling to grasp the inner workings of RxJS and would really benefit from some guidance from more experienced individuals regarding my current issue. ...

Am I effectively implementing async await in TypeScript?

I'm not quite sure if I'm using the async/await functionality correctly in my TypeScript and Protractor code. Looking at the code snippet below, the spec uses await to call the page object, which itself is an async/await function. The page object ...

Leveraging TypeScript to call controller functions from a directive in AngularJS using the "controller as"

I've encountered an issue while trying to call a controller function from a directive, specifically dealing with the "this" context problem. The logService becomes inaccessible when the function is triggered by the directive. Below is the code for th ...

"Mastering the Composition API in Vue 3: A guide to defining props within the setup() method

I created a custom "loading state" mixin specifically for Vue 2: export default { props: { loading: { type: Boolean, default: false }, }, data () { return { innerLoading: false, } }, mounted () { this.innerLo ...

Understanding a compound data type in TypeScript

Hey there, I'm new to TypeScript and I'm facing a challenge in defining the type for an object that might have the following structure at runtime: { "animals" : [ { name: "kittie", color: "blue" }, { name: ...

Angular 2 child route causing application to become unresponsive

Hey there, I'm currently working on setting up child routes for my Angular app and this is what I have so far: import {bootstrap} from 'angular2/platform/browser' import {CommercifyComponent} from './commercify.component' import { ...

Encountering error TS2307 while using gulp-typescript with requirejs and configuring multiple path aliases and packages

Currently, I am working on a substantial project that heavily relies on JavaScript. To enhance its functionality, I am considering incorporating TypeScript into the codebase. While things are running smoothly for the most part, I have encountered an issue ...

Ways to resolve the issue of npm being unable to globally install typescript

While trying to globally install TypeScript using npm sudo npm install -g typescript An error occurs during the installation process with the following message: ENOENT: no such file or directory, chmod '/usr/local/lib/node_modules/typescript/bin/ ...

How to apply an icon image using the background property in CSS in Vue 3

Need help setting background image from the public folder |_public | |_images | |_icon.png |_src |_components |_TheHeader.vue I'm having difficulty trying to set an image as a background in TheHeader.vue using CSS, but the image is located in ...

Consolidate multiple sorting functions into a single function to effectively sort by column

Can someone help me simplify my sorting function for array columns? Currently, I have multiple functions like the one below for each column: sort() { if (this.sortAsc == false) { this.tab.sort((a, b) => { return a.name.localeCompare( ...

Converting JSON Arrays into Typescript Arrays

I am working with a JSON file that contains an array object like this: [ { "VergiNo": "XXXXXXX" }, { "VergiNo": "YYYYYY" }, { "VergiNo": "ZZZZZZ" } ] After importing this JSON file into my Typescript file, import * as companies f ...

Stop the transmission of ts files

Recently, I noticed that when using node JS with Angular-CLI, my .ts files are being transmitted to the client through HTTP. For example, accessing http://localhost/main.ts would deliver my main.ts file to the user. My understanding is that ts files are s ...

I seem to be missing some properties in the request body schema. Why am I receiving an incomplete model for

Seeking assistance in grasping the working of models in loopback4. Here's a model I defined: @model() export class ProductViewConfig extends BaseConfig { @property({ type: 'string', id: true, generated: true, }) _id?: strin ...