0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Vue + Typescript】親コンポーネントとのやりとりには@VModelを使おう

Last updated at Posted at 2021-05-15

###はじめに

v-modelの親子間伝達はvue-property-decorator@VModelを使うと簡単だよ、というお話です。
例がネット上に転がってなかったので、メモ程度に残しておきます。

###前提
@vue/cliの初期化時にtypescriptを指定していれば新しく追加するものはありません。

  • typescript
  • vue-class-component
  • vue-property-decorator

###よくあるやり方

###例

ChildComponent
<template>
    <div>
        <input type="text" v-model="text"/>
    </div>
</template>

<script lang="ts">
import {Vue, Component, VModel} from 'vue-property-decorator'

@Component
export default class ChildComponent extends Vue{
    @VModel({type:String})
    text!:string
}
</script>
ParentComponent
<template>
    <div>
        <child-component v-model="text" />
    </div>
</template>

<script lang="ts">
import { Component, Vue} from 'vue-property-decorator'
import ChildComponent from 'ChildComponent.vue'

@Component({
        components: {
            ChildComponent
        }
    })
export default class ParentComponent extends Vue{
    private text: string = 'aaa'
}
</script>

###注意点
通常のpropsと異なり、親もv-modelでバインドする必要があります。

<!--下の書き方はOK-->
<input type="text" v-model="text"/>
<!--下の書き方はNG-->
<input type="text" :text="text"/>

以上。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?