Typescript Vuejs-与typescipt模型类的双向绑定

Typescript Vuejs-与typescipt模型类的双向绑定,typescript,vue.js,Typescript,Vue.js,我正在尝试基于现有的Typescript类结构和Typescript模型类设置一个新的VueJs应用程序。我需要如何集成vuejs双向绑定可以使用的模型(识别模型上的更新) 我尝试导入模型类“person”,并将其设置为类变量 <template> <form> <input type="text" v-model="person.name" /> {{person.name}} </form> &l

我正在尝试基于现有的Typescript类结构和Typescript模型类设置一个新的VueJs应用程序。我需要如何集成vuejs双向绑定可以使用的模型(识别模型上的更新)

我尝试导入模型类“person”,并将其设置为类变量

<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;
}

{{person.name}
从“@/models/Person”导入{Person};
从“Vue”导入Vue;
从“vue属性装饰器”导入{Component};
@组件({})
导出默认类Home扩展Vue{
公众人物!:公众人物;
创建(){
this.person=新人();
}
}
---以下人士:
出口类人员{
公共名称:字符串;
公众生日:日期;
}
我的期望是,更改“{name}}”的“name”输入字段也会更改。。。
当前仅调用此。$forceUpdate();技巧:(

我认为问题在于你如何定义
人。
中的
:公众人物;
是非空断言运算符,这意味着变量永远不会是
null
未定义的

由于您没有在该表达式中为其赋值,因此您基本上是在编写:

公众人物!:人物=未定义;


我相信,如果您删除创建的函数,然后执行以下操作:

publicperson:person=newperson();
,它将按照您的预期工作


编辑 由于
person
是一个道具,因此需要从实现组件的父级传入一个已经实例化的
person
对象

您的父组件需要如下所示:

<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>
<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>

太好了。非常感谢。这正是问题所在。还有一个问题:在我的解决方案中,人就是道具,我总是会因为反模式而得到错误“避免直接变异道具”。你有什么建议可以避免吗?@SNO如果
person
是道具,那么这实际上会变得更接近你以前拥有的道具。只是为了确保,您有一个父组件,它实现了示例中的组件,并传递了一个
Person
对象,对吗?完全正确:@Prop()Person:Person=new Person();@SNO使用(粗略地)进行了编辑你需要的。道具需要来自父级,不能在你所处的子组件中创建。希望这能向你解释这一点。很好。除了我仍然收到“避免变异道具…”的错误,这正是我需要的。非常感谢