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?

VueコンポーネントとHTML構文

0
Posted at

App.vue

Vueではsrc/App.vueがメインコンポーネント。
scriptでTypeScriptを定義し、templateでHTMLブロックを定義する。
scriptブロックでは、templateブロックで参照できるコンポーネントをimportできる。
templateブロックでは、importしたvueコンポーネントを参照し、HTMLテンプレートに埋め込む事ができる。
コンポーネントにはプロパティを指定する事ができる。
プロパティにより、コンポーネント間での値の受け渡しが可能。

<script setup lang="ts">
import Counter from './components/Counter.vue' // コンポーネントのimport.
</script>

<template>
  <Counter msg="Vite + Vue"/> <!-- コンポーネントを埋め込み、msgプロパティで値を指定 -->
</template>

コンポーネント

App.vueから参照される。
非常に簡単なコンポーネントとして、msgというプロパティを受け取った値を表示し、counterというリアクティブ値を定義して、アクションにより値の変化が動的に反映できることを確認するvueコンポーネントを定義。

<script setup lang="ts">
import { ref, computed } from 'vue';
defineProps<{ msg: string }>() // msgというstring型のプロパティを宣言

const counter = ref(0); // counterというリアクティブオブジェクトを定義(初期値は0)
const doubleCounter = computed(() => counter.value * 2); // リアクティブオブジェクトが変化することにより自動実行される関数をcomputed関数で定義
</script>

<template>
    <section id="center">
        <!-- msgプロパティを表示 -->
        <div>{{ msg }}</div>

        <!-- counterを+1するボタン -->
        <button type="button" class="counter" @click="counter++">
            Count is {{ counter }}
        </button>

        <!-- counter が変化することで自動計算されたdoubleCounterを表示 -->
        <div>Double count is {{ doubleCounter }}</div>
    </section>
</template>

コンセプト

マスタッシュ (mustache)

HTMLベースのテンプレート構文を採用しているVueでは、マスタッシュという二重中括弧で囲った変数をHTMLテンプレートに定義できるようになっている。
コンパイルすると、マスタッシュ変数が実際の変数にマッピングされる。

<script setup lang="ts">
const count = 0;
</script>

<template>
Count is {{ count }}
</template>

リアクティビティ

HTMLテンプレートに定義したマスタッシュ変数は、そのままではプログラムにより値が変化しても画面上では変化しない。
Vueでは、プログラムの状態を監視し、値が変化したことを検出した場合に値を更新するという仕組みがある。これをリアクティビティという。
ref()を使ってリアクティブ値としてオブジェクトを生成することで、このオブジェクト値が変化した時に関連する計算処理が自動実行され、マスタッシュで定義された値が画面上で自動更新される。

<script setup lang="ts">
import { ref, computed } from 'vue';
const counter = ref(0);
</script>

<template>
  <button type="button" class="counter" @click="counter++">
  Count is {{ counter }}
  </button>
</template>
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?