[Vue +TS] Use Two-Way Binding in Vue Using @Model Decorator with TypeScript

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Vue +TS] Use Two-Way Binding in Vue Using @Model Decorator with TypeScript相关的知识,希望对你有一定的参考价值。

Vue models, v-model, allow us to use two-way data binding, which is useful in some cases such as forms. This lesson shows how to use it by creating a custom checkbox component using the @Model decorator in TypeScript.

 

Checkbox:

<template>
  <div>
      <input type="checkbox" :id="id" :checked=checked @change="changed"/> {{label}}
  </div>
</template>

<script lang="ts">
import Vue from ‘vue‘
import { Component, Prop, Model } from ‘vue-property-decorator‘
@Component
export default class MyCheckbox extends Vue {
  @Prop() label: string
  @Prop() id: string

  @Prop()
  @Model(‘change‘) checked: boolean

  changed(ev) {
    this.$emit(‘change‘, ev.target.checked)
  }
}
</script>

 

Parent Component:

<template>
    <div>
        <MyCheckbox :label="checkbox.label" :id="checkbox.id" v-model="checkbox.checked"/>

        {{JSON.stringify(checkbox)}}
    </div>
</template>
<script lang="ts">

import Vue from ‘vue‘
import {Component} from ‘vue-property-decorator‘
import MyCheckbox from ‘./MyCheckBox.vue‘

@Component({
    components: {
        MyCheckbox
    }
})
export default class HelloTs extends Vue {

    checkbox = {
        label: ‘Fancy checkbox‘,
        id: ‘checkbox-id‘,
        checked: true
    }
}
</script>

 

以上是关于[Vue +TS] Use Two-Way Binding in Vue Using @Model Decorator with TypeScript的主要内容,如果未能解决你的问题,请参考以下文章

[Vue + TS] Use Dependency Injection in Vue Using @Inject and @Provide Decorators with TypeScript(代码片

[Typescript Kaop-ts] Use AOP in Vue Components with TypeScript and Kaop-ts

vue-cli3 + ts + vuex

vue 国际化二

如何将 Vue 插件包含到 Vue TypeScript 的模板中?

记一次使用pm2运行node+ts项目,ts-node报错问题To load an ES module, set “type“: “module“ in the package.json or use