0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

初心者から見たVue3コンポーネントの実装のしやすさについて Vision.7

Last updated at Posted at 2024-06-18

Vue3コンポーネントの実装のしやすさについて Vision.7

Vue3のコンポーネントの実装について、前回はVue3コンポーネントの詳細から、
ローカル登録について、まとめました。

前回:ローカル登録

今回は、propsの宣言を以下にまとめます。

なお、Vision2でpropsの受け渡しについて触れましたが
今回はその深掘りとなっています。

Vue3のコンポーネントの詳細3

公式ページ:propsの宣言を読み進めながら、以下のように解釈。

  1. <script setup>を使用する場合の宣言: Vision2のおさらいですが
    単一ファイルコンポーネントで<script setup>を使用する場合、defineProps()マクロを
    使ってpropsを宣言します。

    anyComponent.vue
    <script setup>
    const props = defineProps(['message'])
    
    console.log(props.message)
    </script>
    

  2. <script setup>を使用しない場合の宣言: propsオプションを使って
    propsを宣言します。

    anyComponent.js
    export default {
      props: ['message'],
      setup(props) {
        // setup() は第1引数にpropsを受け取ります。
        console.log(props.message)
      }
    }
    

    defineProps()を使用して宣言する場合でも、単にpropsオプションを使用する場合でも
    vueの裏側では、同じプロパティにアクセスしていることが分かりました。

  3. オブジェクト構文での宣言:
    propsの宣言には、文字列の配列を使用した宣言に加え、オブジェクト構文も
    使用できます。
    <script setup>を使用する場合

    anyComponent2.vue
    <script setup>
    defineProps({
      title: String,
      likes: Number
    })
    </script>
    

    <script setup>を使用しない場合

    anyComponent2.js
    export default {
      props: {
        title: String,
        likes: Number
      }
    }
    

    オブジェクト宣言の構文に含める各プロパティについて
    キーには、propsの名前
    値には、目的の型のコンストラクター関数
    を指定します。

    これはコンポーネントを文書化するだけでなく
    誤った型を渡した時に、ブラウザーのコンソールに警告が表示されるようになり
    コンポーネントを利用する他の開発者のためにもなります。

    公式ページの説明については、オブジェクト宣言の構文を使用することで
    可読性と保守性を上げる効果があると読み取りました。

  4. 型アノテーションでの宣言:
    TypeScriptと<script setup>の組み合わせを用いる場合、型アノテーションを
    そのまま使ってpropsを宣言することも可能です:

    anyComponent3.vue
    <script setup lang="ts">
    defineProps<{
      title?: string
      likes?: number
    }>()
    </script>
    

公式ページには、更に以下のページへのリンクが張られていました。
記事にするのは、ずっと後になりそうですね。

詳細: コンポーネント props の型付け

今回はPropの深掘りについて、まだようやく第一歩を踏み出したというレベルですね。
先は長そうですが、難易度はまだ高くないです。

次回:props渡しの詳細

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?