はじめに
Hello World とコメント
Vue 3 のアプリは、createApp() と mount() から DOM 要素へ始まります。リア クティブなデータを表示するのが、二重の波括弧 {{ }} による補間です。HTML のコメントはレンダリングされた DOM に現れます。漏れてほしくないコメントには、<script> ブロックの内側で /* */ を使いましょう。
<!-- index.html -->
<div id="app">
<p>{{ message }}</p>
<!-- This is an HTML comment, visible in DOM -->
</div>
<script type="module">
import { createApp } from 'vue'
createApp({
data() {
return { message: 'Hello Vue 3!' }
}
}).mount('#app')
</script>SFC の構造(Single File Component)
SFC は、template、script、style を 1 つの .vue ファイルに束ねます。Composition API に推奨される構文であるのが、<script setup> で — 簡潔でボイラープレートゼロです。現在のコンポーネントにのみ適用されるのが、scoped のスタイルで、漏れを防ぎます。各 SFC は、JavaScript のモジュールへコンパイルされます。
<template>
<button @click="count++">Count: {{ count }}</button>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
<style scoped>
button { color: #42B883; }
</style>アプリのインスタンスとマウント
createApp は、自身にスコープされたアプリケーションのインスタンスを返します — グローバルな Vue の状態がないため、1 つのページに複数の独立したアプリをマウントできます。mount() を呼ぶ前に、プラグインを登録し、グローバルな値を提供し、config を設定しましょう。マウントの後の config の変更は、効力を持ちません。
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// global config / plugins before mounting
app.config.errorHandler = (err) => console.error(err)
app.provide('apiKey', '12345')
app.mount('#app')プロジェクトのスキャフォールディング(Vite)
npm create vue@latest が公式のスキャフォールディングツールであり、オプションで TypeScript、Router、Pinia、Vitest のセットアップを提供します。開発サーバーの即時起動と HMR に、Vite を使います。Vue の意見なしの最小テンプレートが欲しいなら、より低レベルのツールである create-vite を。
# scaffold a new Vue project with Vite
npm create vue@latest my-app
cd my-app
npm install
npm run dev # start dev server (HMR)
npm run build # production build to /dist
# or with create-vite directly
npm create vite@latest my-app -- --template vue-tsdefineOptions と defineProps
defineProps、defineEmits、defineOptions はコンパイル時のマクロです — インポートが不要です。実行時の検証付きでコンポーネントの prop の契約を宣言するのが、defineProps です。<script setup> では直接表現できない、name、inheritAttrs、その他のオプションを設定させてくれるのが、defineOptions です。
<script setup>
// declare props with types and defaults
const props = defineProps({
title: String,
count: { type: Number, default: 0 }
})
// declare emits
const emit = defineEmits(['update', 'delete'])
// additional non-reactive options
defineOptions({ name: 'MyButton', inheritAttrs: false })
</script>テンプレートの構文
テキストの補間
{{ }} は、テキストを安全に表示します(HTML エスケープされます)。静的なコンテンツのために、最初のレンダリングの後でバインディングを凍結するのが、v-once です。生の HTML を注入するのが、v-html で — XSS を避けるため、信頼されたコンテンツにだけ使いましょう。{{ }} の内側では、任意の単一の JavaScript の式が使えますが、代入や var 宣言のような文は使えません。
<template>
<p>{{ message }}</p>
<!-- renders the value of message -->
<!-- one-time binding (no updates after render) -->
<span v-once>{{ initialCount }}</span>
<!-- raw HTML (sanitize to avoid XSS!) -->
<div v-html="rawHtmlContent"></div>
<!-- expressions are supported -->
<p>{{ count * 2 }}</p>
<p>{{ isReady ? 'Yes' : 'No' }}</p>
<p>{{ message.split('').reverse().join('') }}</p>
</template>属性のバインディング
属性をリアクティブにバインドするのが、v-bind(省略形 :)です。class のためには、オブジェクト(truthy のキーが適用されます)、配列、文字列を渡せます。style は、camelCase か kebab-case のキーを 持つオブジェクトを受け付けます。属性名自体をリアクティブにさせてくれるのが、動的引数の構文 :[expr] です — イベント名やローカライズされた属性に有用です。
<template>
<!-- bind an attribute -->
<img v-bind:src="imageUrl" />
<img :src="imageUrl" /> <!-- shorthand -->
<!-- bind class -->
<div :class="{ active: isActive, error: hasError }"></div>
<div :class="['btn', isActive && 'active']"></div>
<!-- bind style -->
<div :style="{ color: textColor, fontSize: size + 'px' }"></div>
<!-- dynamic attribute name -->
<button :[eventName]="handler">Click</button>
</template>ブールと複数値の属性
disabled や checked のようなブール属性のために、値が truthy のときだけ Vue が属性を表示します。特別であるのが、class と style です:置き換えでなく、静的とバインドされた値をマージします。フォームの入力のためには、:value と @input を手動でバインドするのでなく、v-model を優先しましょう。