LoginSignup
3
1

More than 1 year has passed since last update.

【Vue】Vue3(Composition API) × TypeScript チートシート

Last updated at Posted at 2023-03-27

単一コンポーネントファイル(.vue)の記述

App.vue
<template>
    <h1>{{ title }}</h1>
</template>

<script setup lang="ts">
    const title = "Hello World!";
</script>

<style scoped>
    .h1 {
        color: red;
    }
</style>

主要ディレクティブ一覧

名称 説明
v-on:[イベント名]
(省略記号 @ )
要素にイベントリスナーを追加する.
v-bind:[プロパティ名]
(省略記号 : )
要素のプロパティに対してVueインスタンスを紐づける.
v-if 条件に基づき,DOMに要素を追加するかを決定する.
v-else-ifやv-elseも合わせて使用可能
v-for Vueインスタンスのプロパティをもとに,要素を繰り返しDOMに追加する.
v-model input要素への入力値とVueインスタンスの値を紐づける.
双方向データバインディング
v-show 条件に基づきdisplayプロパティを操作し,要素を表示するかどうか決定する.

親から子コンポーネントへのデータの受け渡し(Props)

  • 親コンポーネント
    • scriptで子コンポーネントをインポートする.
    • template内でタグを使ってDOMに追加する.(ケバブケースに自動で変換される.)
    • 子コンポーネントへのデータの受け渡しはプロパティを利用する.(Vueプロパティを使う場合はv-bindを用いる)
ParentComp.vue
<template>
    <child-comp
        title="たいとる"
        :content="msg"
    >
    </child-comp>
</template>

<script setup lang="ts">
    import ChildComponent from "./component/ChildComp.vue";
    msg = "こんてんつ";
</script>
  • 子コンポーネント
    • 親から受け取りたいデータを持つインターフェースを定義する.
    • defineProps()関数を実行する.defineProps<インターフェース名>()
Vue.ChildComp.vue
<template>
    <div class="child">
        <h3>{{ title }}</h3>
        <p>{{ content }}</p>
    </div>
</template>

<script setup lang="ts">
    interface Props {
        title: string;
        content: string;
    }
    defineProps<Props>();
</script>

子から親コンポーネントへのデータの受け渡し(Emit)

子から親へのデータの受け渡しはイベント処理を通じて行う.

  • 親コンポーネント
    • scriptで子コンポーネントをインポートする.
    • template内でv-onディレクティブを使って,子コンポネントで定義したイベントと親コンポーネントの関数を紐づける.
    • 紐づけた関数の引数で,子コンポーネント内でイベントと一緒に定義したデータを受け取る.
ParentComp.vue
<template>
    <child-comp @sendMessage=""></child-comp>
</template>

<script setup lang="ts">
    import ChildComp from "./component/ChildComp.vue";
    
</script>
  • 子コンポーネント
    • 親へ渡したいデータを持つインターフェースを定義する.(event: "イベント名", 引数1, 引数2...)
    • defineEmits()関数を実行する.defineEmits<インターフェース名>()
    • イベントを発生させる要素と関数を用意し,関数内でemit("イベント名", 引数)を実行する.
ChildComp.vue
<template>
    <button @click="buttonClicked"></button>
</template>

<script setup lang="ts">
    interface Emits {
        (event: "sendMessage", msg: msg): void;
    }
    const emit = defineEmits<Emits>();
    const buttonClicked = () => {
        emit("sendMessage", msg);
    }
    msg = "こんにちは";
</script>
3
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
3
1