Using Vue.js for bidirectional data binding with TypeScript model classes

I am in the process of setting up a new VueJs application based on an existing Typescript-class structure with typescript model-classes. How should I integrate my models so that two-way-binding in vuejs can function properly and recognize updates on the model?

I attempted to import the model class "person" and declared it as a class variable.

<template>
        <form>
            <input type="text" v-model="person.name" />
            {{person.name}}
        </form>
    </template>

    <script lang="ts">
        import {Person} from '@/models/person';
        import Vue from 'vue';
        import {Component} from 'vue-property-decorator';

        @Component({})
        export default class Home extends Vue{
            public person! : Person;

            created(){
                this.person = new Person();
            }
        }
    </script>


    --- Following person.ts:

    export class Person{
        public name : string;
        public birthday: Date;
    }

My hope is that by changing the input field for "name", the '{{name}}' will also change... Currently, only calling this.$forceUpdate(); seems to do the trick :(

Answer №1

It seems like the issue lies in how you have defined the variable person. The exclamation mark ! in public person! : Person; indicates that the variable will never be null or undefined.

However, since you haven't assigned it a value in that statement, essentially you are doing:

public person!: Person = undefined;


To resolve this, consider removing the created function and simply initializing the variable like so:

public person: Person = new Person();
, which should function as intended.


Edit

As person is a prop, make sure to pass an instantiated Person object from the parent component into your child component.

Your parent component structure could appear similar to this:

<template>
  <div>
    <home :person="person"></home>
  </div>
</template>

<script lang="ts">
import Home from "@/components/home";
import Person from "@/models/person";

@Component({})
export default class Parent extends Vue {
  private person: Person = new Person();
}
</script>

Subsequently, in the child component (such as the Home component in your scenario), you would utilize it in this manner:

<template>
    <form>
        <input type="text" v-model="person.name" />
        {{person.name}}
    </form>
</template>

<script lang="ts">
    import {Person} from '@/models/person';
    import {Vue, Component} from 'vue-property-decorator';

    @Component({})
    export default class Home extends Vue {
        @Prop()
        public person!: Person;
    }
</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

What is the best way to create a feature in Vue that filters options in real-time as we type into a

In my Vue application, I am trying to implement dynamic filtering for the options in a search box as the user types. Currently, the search box displays the entire list of options without any filtering happening even when the user is typing. <el-form-it ...

What is preventing the exclusion of the null type in this specific situation within Typescript?

type NonNullableCopy<O> = { [p in keyof O] -?: O[p] extends null | undefined ? never : O[p]; }; type Adsa = {a?: number | null} type Basda = NonNullableCopy<Adsa> let asd : Basda = { a: null // Still valid. No errors } Although it see ...

Unable to access the 'mobile' property as it is not defined - Vue/Vuetify/Storybook

I am encountering an issue with the "canvas" screen on my storybook's Vue and Vuetify story. While other components are functioning correctly, this particular one is not working as expected. It appears that my story is unable to identify the 'mob ...

Issue transferring information between non-related components in an Angular 8 application unrelated to BehaviorSubject

Encountering an issue with passing data between unrelated components using Services and BehaviorSubject. The problem arises when the data is received, as the value of the variable Behavior arrives empty (""), despite the components having no apparent conne ...

Building a Multi-Language React Application with Real-Time Data

Is there a way for users to input data in their chosen language (English, French, German) and have that data saved in all three languages in the Database so they can view it based on their language selection? I've experimented with React-Intl and I18 ...

Connect a function to a functional component within React

When it comes to a class component, you have the ability to define custom functions within the component like so: class Block extends React.Component { public static customFunction1(){ return whatever; } public static customFunction2(){ re ...

Utilizing Environment Variables during the build process in a VueJS project

During the build stage of a CI job for my VueJS app, I am attempting to utilize an environment variable provided by GitLab CI called CI_COMMIT_SHORT_SHA. build: image: node:latest stage: build variables: CI_COMMIT_SHORT_SHA: "$CI_COMMIT_SHORT_S ...

Exploring ways to set up dynamic child routes for Vue routers

I am experimenting with a code snippet like the one below { path: "/portfolio", component: () => import("../common/components/Layout/Layout/Profile/ProfileLayout"), meta: { requiresAuth: false }, children: [ ...

What is the best method to compare two times and determine if they fall on the same date within an Angular 2/4 application? The time should be in the format of "HH:mm AM

Is there a way to validate if my time period falls on the same date? let startTime = currentSelection.startTimeHr + ":" + currentSelection.startTimeMin + " " + currentSelection.startTimeAMPM; let endTime = currentSelection.stopTimeHr + ":" + currentSele ...

What is the best way to send an enum from a parent component to a child component in

I'm trying to send an enum from a parent component to a child component. This is the enum in question: export enum Status { A = 'A', B = 'B', C = 'C' } Here's the child component code snippet: @Component({ ...

What causes the ignoring of config.proxy in axios requests while working on a webpack project?

My objective I am aiming to make a request using [email protected] with full efficiency through an http proxy (squid). My project is built on Vue and uses the webpack template. I initialized it with vue init webpack proxytest The challenge Despite ...

Error encountered during an object casting operation at runtime

I am currently tackling a project in Typescript. Even though the code compiles without errors and adheres to all theoretical principles, it fails to function correctly at Runtime. The root cause of this issue lies in the fact that TypeScript is transpil ...

When hovering over the Angular div, a container will appear. However, the container suddenly disappears when attempting to hover over it further

Can anyone help with setting up a container to display when hovering over text, but also stay visible if the user hovers over the container itself? Currently, it disappears when hovering over the container. Here is the HTML: <p (mouseenter)="displ ...

Enhancements to managing universal configuration object across the entire application

My current project involves working on an application with multiple products. To streamline product-specific configuration and eliminate the need for excessive if-else statements, I am looking to implement product-specific config keys that are consistently ...

Having trouble retrieving directive parameters in Vue.js?

Vue.directive('customselect', { params: ['selectedTask'], bind: function () { var that = this; $(this.el) .select2() .on('change', function () { that.set(this.value); if (!this.name.matc ...

Creating a map in Typescript initialized with a JSON object

In my Typescript class, there is a map that I'm trying to initialize: public map:Map<string,string>; constructor() { let jsonString = { "peureo" : "dsdlsdksd" }; this.map = jsonString; } The issue I'm encounte ...

Is there a way for me to use TypeScript to infer the type of the value returned by Map.get()?

type FuncType<O extends Object> = (option: O) => boolean export const funcMap: Map<string, Function> = new Map() const func1: FuncType<Object> = () => true const func2: FuncType<{prop: number}> = ({ prop }) => prop !== 0 ...

What is the best way to invoke a computed property using dynamic styling?

Looking for a way to dynamically style an Ant Design Vue button within a table row of an Ant Design table? <template #status="{ text }"> <a-button ghost :style="{'border-color': getColor(text) }"> </a-b ...

What is the best way to incorporate node_module during the iOS build process in Ionic 2?

Looking to implement an autosize module for automatic resizing of an ion-textarea. Module: Following the installation instructions, I tested it in the browser (ionic serve) and on my iPhone (ionic build ios => run with xcode). Browser: The module wor ...

Why does my VueJS method only execute after I save changes in VS Code instead of reloading the page? Can someone provide assistance?

Whenever I refresh the page, the console.log inside the method does not get executed until I make a change in VSC and save it. Is the show/hide modal for the form causing this issue? I tested removing the toggle but the problem persisted. Please refer to ...