How to achieve two-way binding of v-model object in Vue class-style component using TypeScript

I am looking to develop a custom component in Vue CLI that allows me to utilize v-model for passing a value or object to the component. With v-model binding, I can update the passed value in the parent component by either checking a checkbox or clicking a button to set the value to true.

Here's how it would look in the app code:

<test v-model="content"></test>
    <br />
    selected: {{content}}

The Test component is structured as follows:

<template>
  <div>
    <v-text-field label="Regular" v-model="checkval" disabled></v-text-field>

    <input
      type="checkbox"
      v-bind:checked="checkval"
      v-on:change="$emit('change', $event.target.checked)"
    />

    <v-btn @click="$emit('change', true)">Make true</v-btn>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Model, Prop } from "vue-property-decorator";

@Component({
  model: {
    prop: "checkval",
    event: "change"
  },
  props: {
    checkval: Boolean
  }
})

export default class test extends Vue {}
</script>

Now, my aim is to take it a step further and implement my component using a "class style" approach and enable two-way binding with an object. When I attempted this, the previous code with Boolean worked fine, but trying with an object did not yield success:

export class myobject {
    checkval!: boolean;
    test!: String;
}

@Component
export default class test extends Vue {
    @Prop() checkval: Boolean = false;
    @Model() model: myobject = {
        checkval: true,
        test: "checkval"
    };
}

My questions now are:

  1. How should I proceed when binding an object?
  2. Is there a way to avoid using Emit and simply set the variable like checkval = true or model.checkval = true ?
  3. If I do need to use Emit, what would be the correct implementation for the button, such as:
    <v-btn @click="$emit('change', {...this.model, checkval: true})">
    ?

Answer №1

After encountering the same issue, I finally discovered the solution on the vue-property-decorator GitHub page:

@Model(event?: string, options: (PropOptions | Constructor[] | Constructor) = {}) decorator

import { Vue, Component, Model } from 'vue-property-decorator'

@Component
export default class YourComponent extends Vue {
  @Model('change', { type: Boolean }) readonly checked!: boolean
}

This code snippet is equivalent to:

export default {
  model: {
    prop: 'checked',
    event: 'change'
  },
  props: {
    checked: {
      type: Boolean
    }
  }
}

The @Model property can also set the type property based on its type definition via reflect-metadata.

Answer №2

Consider utilizing the VModel feature for your project.

import { Vue, Component, VModel } from 'vue-property-decorator'

@Component
export default class MyComponent extends Vue {
  @VModel({ type: String }) username!: string
}

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 suggestions do you have for standout TypeScript presentations?

Currently, I am enrolled in a TypeScript program and keen to experiment with some demonstrations to enhance my comprehension of the topics. Could anyone recommend showcases ranging from beginner level to more advanced stages? Appreciate your assistance. ...

angular8StylePreprocessorSettings

I'm currently trying to implement the approach found on this tutorial in order to import scss files through stylePreprocessorOptions in Angular 8. However, I'm encountering an error stating that the file cannot be found. Any suggestions on how to ...

Access the configuration setting in the plugin settings for retrieving sales channel information

Is there a way to access specific values from the plugin configuration related to a particular sales channel? I'm trying to validate an API token, but can only retrieve the value set for all sales channels. I'm not sure how my custom admin compon ...

When working with Vue JS, which is more performant and preferable to use: making direct changes to state in Pinia or using $patch()?

Hey guys, I've been working with Pinia and Vuejs 3, and I'm curious about the performance impact of using $patch(). Can anyone shed some light on this? What is considered the best practice when it comes to this situation? For instance, take a l ...

Linking Vue data to various divs or tables for mounting

Just starting out with vue Attempting to design a basic table or multiple divs (5 rows by 5 columns) I want to bind data to each of those td\div elements If necessary, I'm open to changing the data format that's coming in, but my vision i ...

Utilize Vuex to streamline and organize multiple requests within a group

Our current Vue + Vuex application is designed with numerous custom components on each page, all connected to MongoDB as our database. Every component fetches data from an API endpoint on initialization: async loadData() { const data = await getData(&a ...

Create a TypeScript variable that has a type definition allowing for the inclusion of null

I am dealing with the type definition below, which was created by a framework: export type SecretCategory = { 'Password' : null } | { 'Note' : null } | { 'Document' : null }; What is the best way to declare a variable of type ...

Changing the color of a Chart.js chart in Angular: A step-by-step guide

I've been struggling to change the color of my chart without success. Any assistance on this matter would be greatly appreciated. Despite trying to assign color values to datasets, I am still unable to achieve the desired result. This is a snippet f ...

Cypress has the ability to exclude certain elements from its testing

How do I locate a clickable element using the cypress tool? The clickable element always contains the text "Login" and is nested inside the container div. The challenge lies in not knowing whether it's an <button>, <a>, or <input type=& ...

Creating dynamic forms in Vue using v-for

I'm currently experimenting with creating dynamic form fields using v-for and vuex. My approach involves nesting a v-for inside another v-for. The process of adding new form fields works smoothly, but I encountered an issue when attempting to delete t ...

Encountered an error: Object(...) does not conform to function standards in the handleChange method

When using JavaScript, everything works fine. However, when trying to implement TypeScript with the handleChange function, an error is consistently thrown whenever something is typed into the entries. The error message reads: "TypeError not captured: Objec ...

What happens when `$router.replace` bypasses server-side rendering?

I am facing an issue with a page (e.g. /index) that contains a button like: <button @click="addItemAndRedirect"> {{ $store.state.items.length }} </button> and the method is as follows: methods: { addItemAndRedirect () { t ...

Issue with Pagination in Angular 7: Functioning Error

I am having trouble with my pagination setup. I am struggling to understand how to properly pass this.total = res.totalPage; from the Component to the Service so that it can count the pages correctly. Currently, it is only displaying one page as shown in t ...

The input value fails to update after the method is called

I am working on developing a todo-list application and here is the code I have so far: HTML: <div class="divPadder"> <input ref="makePlaceholderEmpty" class="inputBoxSize" type="text" :placeholder="placeholder"v-model="task"> <ul> ...

How to only disable checkboxes that are currently checked in Angular 8

click here to view an image**I would like to know how I can disable only the selected/checked items on a p-listbox in Angular 8. Is it possible to achieve this by adding a specific property or using CSS? Currently, when I try to add the [disabled] proper ...

Step-by-step guide on updating the home page content in angular4 upon signing up with the user page

The home page and user page contents are both displayed on the home page itself. In the header section, I have a SignIn and SignUp form from the home.html file. Additionally, there is another Signup form from the user page. This form includes 3 buttons: on ...

Angular - Showing validation messages post successful execution of two functions

I have encountered an issue with my form submission process involving two functions. When both functions succeed, I want to display a successful validation message. However, currently the success message is displayed even if the second function fails. How ...

tips for accessing dynamic key pair value data in Angular

I am facing an issue where I cannot retrieve the dynamic key pair value from the dynamic JSON. Below is my JSON: var d = { "pexels-photo.jpeg": { "information": "laptop", "desc": { "mimetype": "image/jpeg", "id" ...

Angular data binding between an input element and a span element

What is the best way to connect input texts with the innerHTML of a span in Angular6? Typescript file ... finance_fullname: string; ... Template file <input type="text" id="finance_fullname" [(ngModel)]="finance_fullname"> <span class="fullnam ...

TypeORM is failing to create a table upon initialization

Recently, I delved into the realm of typescript and decided to explore TypeORM for backend development. My current project involves building a CRUD API using typeORM and postgreSQL. After configuring everything initially, I ran the application only to rea ...