Skip to content

Vue 3 チートシート

ユーザーインターフェイスを構築するためのプログレッシブ JavaScript フレームワーク。

01

はじめに

Hello World とコメント

Vue 3 のアプリは、createApp() と mount() から DOM 要素へ始まります。リアクティブなデータを表示するのが、二重の波括弧 {{ }} による補間です。HTML のコメントはレンダリングされた DOM に現れます。漏れてほしくないコメントには、<script> ブロックの内側で /* */ を使いましょう。

vue3
<!-- 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 のモジュールへコンパイルされます。

vue3
<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 の変更は、効力を持ちません。

vue3
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 を。

vue3
# 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-ts

defineOptions と defineProps

defineProps、defineEmits、defineOptions はコンパイル時のマクロです — インポートが不要です。実行時の検証付きでコンポーネントの prop の契約を宣言するのが、defineProps です。<script setup> では直接表現できない、name、inheritAttrs、その他のオプションを設定させてくれるのが、defineOptions です。

vue3
<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>
02

テンプレートの構文

テキストの補間

{{ }} は、テキストを安全に表示します(HTML エスケープされます)。静的なコンテンツのために、最初のレンダリングの後でバインディングを凍結するのが、v-once です。生の HTML を注入するのが、v-html で — XSS を避けるため、信頼されたコンテンツにだけ使いましょう。{{ }} の内側では、任意の単一の JavaScript の式が使えますが、代入や var 宣言のような文は使えません。

vue3
<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] です — イベント名やローカライズされた属性に有用です。

vue3
<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 を優先しましょう。

vue3
<template>
  <!-- boolean attribute: presence depends on value -->
  <input :disabled="isDisabled" />
  <button :disabled="!canSubmit">Submit</button>

  <!-- class merging: bound class merges with static class -->
  <div class="card" :class="{ highlighted: isFeatured }"></div>

  <!-- style merging: bound style merges with static style -->
  <div style="color: red" :style="{ fontSize: '14px' }"></div>

  <!-- form attributes: value is bound with v-model instead -->
  <input v-model="text" />
</template>

修飾子と式

ドットで示される後置であるのが、修飾子で、特別な扱いを示します。対応する DOM メソッドでハンドラを包むのが、イベントの修飾子(.prevent、.stop、.once、.self)です。キーによりイベントをフィルタするのが、キーの修飾子(.enter、.esc、.ctrl)です。代入の前に入力値を変換するのが、v-model の修飾子(.trim、.number、.lazy)です。

vue3
<template>
  <!-- .prevent calls event.preventDefault() -->
  <form @submit.prevent="onSubmit">...</form>

  <!-- .stop calls event.stopPropagation() -->
  <button @click.stop="doStuff">Click</button>

  <!-- .once runs handler only one time -->
  <button @click.once="init">Init</button>

  <!-- .trim and .lazy modifiers on v-model -->
  <input v-model.trim="email" />
  <input v-model.lazy="text" />

  <!-- chain multiple modifiers -->
  <input @keyup.enter.ctrl="onCombo" />
</template>

テンプレートの ref

DOM 要素への直接のアクセスを与えてくれるのが、テンプレートの ref です。ref 属性と同じ名前で ref() を宣言しましょう — マウントの後に Vue が DOM ノードを割り当てます。onMounted の内側(かその後)でアクセスしましょう。マウントの前は、ref が null です。v-for のためには、ref が要素の配列になります。リアクティブなデータのフローで十分なとき、refs に手を伸ばすことは避けましょう。

vue3
<script setup>
import { ref, onMounted } from 'vue'

// declare a ref matching the template ref attribute
const inputEl = ref(null)

onMounted(() => {
  // access the DOM node after mount
  inputEl.value.focus()
})
</script>

<template>
  <input ref="inputEl" />
</template>
03

ディレクティブ

v-if / v-else-if / v-else

条件付きで要素を表示するのが、v-if です — DOM へ加えられたり、取り除かれたりします。先行する v-if と連鎖するのが、v-else-if と v-else です。余分なラッパー要素が欲しくないとき、複数の要素を <template v-if> で包みましょう。条件が false のとき、v-if は(DOM の作成により)切り替えのコストが高く、v-show より初期のコストが低いです。

vue3
<template>
  <div v-if="type === 'A'">Type A</div>
  <div v-else-if="type === 'B'">Type B</div>
  <div v-else-if="type === 'C'">Type C</div>
  <div v-else>Unknown type</div>

  <!-- use <template> for invisible wrapper -->
  <template v-if="showHeader">
    <h1>Title</h1>
    <p>Subtitle</p>
  </template>
</template>

v-show 対 v-if

条件がめったに変わらないときに v-if を使いましょう — 要素が破壊され再作成されるため、隠れている間、レンダリングのコストが節約されます。頻繁に切り替えられる要素(タブ、ドロップダウン)には v-show を — 要素が DOM に留まり、display:none だけが切り替わるため、切り替えが安価です。<template> や v-else では、v-show が機能しません。

vue3
<template>
  <!-- v-if removes from DOM when false -->
  <p v-if="isVisible">I'm created/destroyed</p>

  <!-- v-show just toggles display:none -->
  <p v-show="isVisible">I'm always in DOM, just hidden</p>
</template>

<script setup>
import { ref } from 'vue'
const isVisible = ref(true)
</script>

v-for と :key

配列、オブジェクト、数値の範囲を反復するのが、v-for です。track-by の同一性のためには、:key 属性が必須です — 並べ替えの間、Vue が効率的に DOM ノードを再利用できます。キーには、安定した一意の id を使いましょう。配列のインデックスを使ってはいけません(アイテムが動くと壊れます)。同じ要素上で、v-for は v-if より優先度が高いため、1 つの要素に両方使うことは避けましょう。

vue3
<template>
  <!-- iterate over array -->
  <li v-for="item in items" :key="item.id">
    {{ item.name }}
  </li>

  <!-- iterate with index -->
  <li v-for="(item, index) in items" :key="item.id">
    {{ index }}: {{ item.name }}
  </li>

  <!-- iterate over object -->
  <li v-for="(value, key) in user" :key="key">
    {{ key }}: {{ value }}
  </li>

  <!-- range (1 to n) -->
  <span v-for="n in 10" :key="n">{{ n }}</span>
</template>

v-model のバインディング

フォーム入力のための双方向のバインディングであるのが、v-model で、入力値をリアクティブな状態と同期します。単一のチェックボックスがブールにバインドし、同じ v-model を共有する複数のチェックボックスがチェック済み値の配列にバインドします。修飾子を使いましょう:.lazy(input でなく change で同期)、.number(数値へキャスト)、.trim(空白を剥ぎ取ります)。

vue3
<template>
  <!-- text input -->
  <input v-model="text" />

  <!-- multi-line textarea -->
  <textarea v-model="message"></textarea>

  <!-- checkbox (single = boolean, multiple = array) -->
  <input type="checkbox" v-model="isChecked" />
  <input type="checkbox" value="apple" v-model="fruits" />
  <input type="checkbox" value="banana" v-model="fruits" />

  <!-- radio -->
  <input type="radio" value="A" v-model="picked" />

  <!-- select -->
  <select v-model="selected">
    <option value="a">A</option>
    <option value="b">B</option>
  </select>
</template>

カスタムディレクティブ

DOM 要素を直接操作させてくれるのが、カスタムディレクティブです。<script setup> では、vSomething(camelCase)という名前の任意の変数が、テンプレートで v-something として自動的に利用可能です。ディレクティブのオブジェクトには、ライフサイクルのフックがあります:mounted、updated、unmounted などです。リアクティビティが必要なときは、ディレクティブよりコンポーネントを優先しましょう — ディレクティブは、フォーカス、ツールチップ、ドラッグのような低レベルの DOM の作業のためのものです。

vue3
<script setup>
// local directive: function form (mounted + updated)
const vFocus = {
  mounted: (el) => el.focus()
}

// global registration
// app.directive('focus', { mounted: el => el.focus() })
</script>

<template>
  <input v-focus />
</template>
04

算出プロパティ

基本の Computed

依存が変わったときだけ再評価される、キャッシュされたゲッターを作るのが、computed です。メソッドの呼び出しと違い、依存が更新されるまで、繰り返しのアクセスがキャッシュされた値を返します。<script> では .value 経由で、テンプレートでは Vue が自動的にアンラップします。値がリアクティブな状態に依存するときはいつでも、メソッドより computed を使いましょう — より速く宣言的です。

vue3
<script setup>
import { ref, computed } from 'vue'

const firstName = ref('John')
const lastName = ref('Doe')

// computed caches based on dependencies
const fullName = computed(() => {
  return firstName.value + ' ' + lastName.value
})

// access via .value in script
console.log(fullName.value)  // 'John Doe'
</script>

<template>
  <!-- use without .value in template -->
  <p>{{ fullName }}</p>
</template>

書き込み可能な Computed

デフォルトで computed は読み取り専用ですが、ゲッターとセッターを提供できます。.value へ代入すると、セッターが呼ばれます。派生状態への双方向のバインディングに有用です(例:フルネームの入力を first/last の名前のフィールドへ同期し戻す)。無限ループを避けるよう注意しましょう — セッターは、自分自身を再トリガーするような方法で、computed 自身の依存を設定すべきではありません。

vue3
<script setup>
import { ref, computed } from 'vue'

const firstName = ref('John')
const lastName = ref('Doe')

const fullName = computed({
  get() {
    return firstName.value + ' ' + lastName.value
  },
  set(newValue) {
    [firstName.value, lastName.value] = newValue.split(' ')
  }
})

// assignment triggers the setter
fullName.value = 'Jane Smith'
</script>

Computed 対 Methods

算出プロパティは、依存に基づき結果をキャッシュします — items が変わったときだけ再実行します。何が変わったかにかかわらず、毎レンダリングで再実行されるのが、メソッドです。リアクティブな状態から派生する値には、computed を、パラメータを取るか副作用を持つアクションには、メソッドを使いましょう。意図もより明確になります:「この値は派生です」対「このことをする」です。

vue3
<script setup>
import { ref, computed } from 'vue'

const items = ref([1, 2, 3, 4, 5])

// computed: cached, re-runs only if items changes
const doubled = computed(() =>
  items.value.map(x => x * 2)
)

// method: re-runs on every render
function getDoubled() {
  return items.value.map(x => x * 2)
}
</script>

<template>
  <!-- cached, no recompute on unrelated re-renders -->
  <p>{{ doubled }}</p>

  <!-- re-invoked on every render -->
  <p>{{ getDoubled() }}</p>
</template>

Getter の computed の落とし穴

computed のゲッターは純粋でなければなりません:副作用なし(ミューテーション、async、フェッチなし)です。Date.now() や Math.random() を呼んではいけません — リアクティブでないため、computed は更新されません。副作用が必要なら、代わりに watcher を使いましょう。async が必要なら、computed は await しません — watch + ref を、または Suspense 付きの async setup を使いましょう。

vue3
<script setup>
import { ref, computed } from 'vue'

const date = ref(new Date())

// BAD: non-reactive Date.now() — won't update
const badTime = computed(() => Date.now())

// BAD: side effect inside computed
const count = ref(0)
const bad = computed(() => {
  count.value++   // never mutate state in computed!
  return count.value
})

// GOOD: pure function of reactive state
const formatted = computed(() =>
  date.value.toLocaleDateString()
)
</script>

Options API の Computed

Options API では、computed オプションで算出プロパティを宣言しましょう。this.total としてアクセスされます(.value も括弧もなし)— Vue が自動的にアンラップします。書き込み可能な computed が、get/set の関数を使います。算出プロパティは、data と methods と共にコンポーネントのインスタンス上に公開され、すべて this でアクセスできます。

vue3
<script>
export default {
  data() {
    return { price: 100, quantity: 2 }
  },
  computed: {
    total() {
      return this.price * this.quantity
    },
    discounted: {
      get() { return this.total * 0.9 },
      set(v) { this.price = v / 0.9 / this.quantity }
    }
  },
  methods: {
    checkout() { console.log(this.total) }
  }
}
</script>
05

ウォッチャー

基本の watch

監視されたソースが変わると、コールバックが走るのが、watch です。ソースは、ref、(ゲッター経由の)リアクティブオブジェクトのプロパティ、ソースの配列であり得ます。コールバックが (newValue, oldValue) を受け取ります。ネストしたリアクティブなプロパティを監視するには、ゲッター () => x.y を使いましょう。ウォッチャーは副作用(fetch、ログ、永続化)のためのものです — 状態を派生させるためでなく(それには computed を使います)。

vue3
<script setup>
import { ref, watch } from 'vue'

const question = ref('')

// watch a ref
watch(question, (newValue, oldValue) => {
  console.log('changed from', oldValue, 'to', newValue)
})

// watch a getter (computed source)
watch(
  () => question.value.length,
  (newLen) => {
    if (newLen > 100) console.warn('Too long!')
  }
)
</script>

Deep Watch と Immediate

オブジェクトの任意のネストしたプロパティの変化で watch を発火させるのが、deep: true です — 有用ですが、大きい構造では高コストです。セットアップで直ちにコールバックを発火させるのが、immediate: true です(最初の呼び出しで oldValue が undefined です)。巨大なオブジェクトでの deep watch を避けましょう — より良いパフォーマンスのために、特定のゲッター () => obj.specificField を監視するほうを優先します。

vue3
<script setup>
import { reactive, watch } from 'vue'

const user = reactive({
  name: 'Alice',
  address: { city: 'NYC', zip: '10001' }
})

// deep: watch nested property changes
watch(
  () => user.address,
  (newAddr) => console.log('address changed', newAddr),
  { deep: true }
)

// immediate: run callback right away
watch(
  user,
  (val) => saveToServer(val),
  { deep: true, immediate: true }
)
</script>

watchEffect(自動追跡)

直ちにコールバックを走らせ、内側でアクセスされた任意のリアクティブな依存を自動追跡するのが、watchEffect です。追跡された依存のいずれかが変わるたび、コールバックが再実行されます。watch と違い、ソースを指定しません — 推論されます。oldValue が必要なく、自動の依存追跡が欲しいとき、watchEffect を使いましょう。複数のリアクティブなソースを読む購読のセットアップに有用です。

vue3
<script setup>
import { ref, watchEffect } from 'vue'

const a = ref(1)
const b = ref(2)

// runs immediately and tracks dependencies automatically
watchEffect(() => {
  console.log('a + b =', a.value + b.value)
})
// logs: a + b = 3

a.value = 10  // logs: a + b = 12

// stop the watcher
const stop = watchEffect(() => { /* ... */ })
stop()  // cleanup
</script>

watch 対 watchEffect

必要なものが oldValue、遅延実行(初期の実行をスキップ)、特定のソースの明示的な監視なら、watch を選びましょう。直ちに実行したい、oldValue が不要、複数のリアクティブな値に触れる副作用があり自動追跡が欲しいなら、watchEffect を選びましょう。配列のソース付きの watch が、コールバックで新旧の値の配列を与えます。

vue3
<script setup>
import { ref, watch, watchEffect } from 'vue'

const count = ref(0)

// watch: lazy, explicit source, has oldValue
watch(count, (newVal, oldVal) => {
  console.log('count changed:', oldVal, '->', newVal)
})

// watchEffect: eager, auto-tracked, no oldValue
watchEffect(() => {
  console.log('count is', count.value)
})
// logs immediately: count is 0

// watch multiple sources
const a = ref(1), b = ref(2)
watch([a, b], ([newA, newB], [oldA, oldB]) => {
  console.log('a or b changed')
})
</script>

Watcher のクリーンアップと Flush

(第 3 引数の)onCleanup コールバックは、次の watcher の呼び出しの前に走るクリーンアップ関数を登録します — 実行中のリクエストのキャンセル、タイマーのクリア、購読解除に最適です。Vue が DOM を更新した後に watcher を走らせるのが、flush: 'post' です(更新された DOM を読む必要があるとき有用)。依存の変化で同期的に走るのが、「sync」です — めったに必要なく、パフォーマンスの問題を引き起こし得ます。

vue3
<script setup>
import { ref, watch } from 'vue'

const id = ref(1)

// cleanup function: runs before next callback
watch(id, (newId, oldId, onCleanup) => {
  const controller = new AbortController()
  fetch(`/api/user/${newId}`, { signal: controller.signal })
    .then(r => r.json())

  // cancel previous request when id changes again
  onCleanup(() => controller.abort())
}, { flush: 'post' })

// flush: 'pre' (default) | 'post' (after DOM update) | 'sync'
</script>
06

条件付きレンダリング

v-if 対 v-show

DOM から要素を本当に加えたり取り除いたりするのが、v-if です — 初期のコストが高いが、隠れている間のコストがゼロです。常に要素を表示し、display:none を切り替えるのが、v-show で — 切り替えが安価ですが、隠れていても要素が存在します。めったに変わらない条件のためには(か隠れた要素が存在すべきでないとき)、v-if を。タブ、ドロップダウン、モーダルのような頻繁に切り替えられる UI には、v-show を。

vue3
<template>
  <!-- v-if: element removed from DOM when false -->
  <div v-if="isLoggedIn">Welcome back</div>

  <!-- v-show: element stays, display toggles -->
  <div v-show="isLoggedIn">Welcome back</div>
</template>

<!-- v-show compiles to: -->
<!-- <div style="display: none;">Welcome back</div> when false -->

<!-- v-if does not render the element at all when false -->

v-else の連鎖付きの v-if

v-else-if と v-else は、v-if(か別の v-else-if)の要素の直後に来なければなりません — それらの間に他の要素があってはいけません。連鎖は上から下へ評価し、最初の truthy な条件で止まります。残りのすべてのケースを捉えるのが、最後の v-else です。ステータスベースの UI(ローディング、エラー、空、成功)に最適なパターンが、これです。

vue3
<template>
  <div v-if="status === 'loading'">Loading...</div>
  <div v-else-if="status === 'error'">Error occurred</div>
  <div v-else-if="status === 'empty'">No items</div>
  <div v-else>
    <ul>
      <li v-for="item in items" :key="item.id">{{ item.name }}</li>
    </ul>
  </div>
</template>

v-if の <template> ラッパー

DOM へ表示されない論理的なラッパーであるのが、<template> です — 余分な HTML を加えずに、複数の要素を 1 つの v-if や v-for の下でグループ化するのに最適です。マークアップがセマンティックに保たれます(余分な div なし)。template 上の v-for のためには、template 要素自体にまだ :key が必要です。

vue3
<template>
  <!-- group elements under one condition, no wrapper div -->
  <template v-if="showProfile">
    <h2>{{ user.name }}</h2>
    <p>{{ user.bio }}</p>
    <button @click="edit">Edit</button>
  </template>

  <!-- combine v-if with v-for on template -->
  <template v-for="item in items" :key="item.id">
    <dt>{{ item.term }}</dt>
    <dd>{{ item.def }}</dd>
  </template>
</template>

v-if 対 v-for の優先度

同じ要素上で v-if と v-for を使ってはいけません。Vue 3 では、v-if の優先度が高いため、v-for の前に走ります — ループ変数がまだ利用できず、エラーになります。代わりに、(優先される)computed プロパティかインラインの .filter() で配列をフィルタしましょう。必ずなら、内側の v-if 付きの <template v-for> を包んで使いましょう。

vue3
<template>
  <!-- AVOID: v-if and v-for on same element -->
  <!-- In Vue 3, v-if has higher priority than v-for -->
  <!-- so 'item' is not defined when v-if evaluates -->
  <li v-for="item in items" v-if="item.active" :key="item.id">
    {{ item.name }}
  </li>

  <!-- GOOD: filter first, then iterate -->
  <li
    v-for="item in items.filter(i => i.active)"
    :key="item.id"
  >
    {{ item.name }}
  </li>

  <!-- BEST: use computed for the filtered list -->
</template>

v-if との Transition

enter/leave をアニメーション化するには、v-if(か v-show)の要素を <Transition> で包みましょう。Vue が適切なタイミングでクラスを加えます:v-enter-from、v-enter-active、v-enter-to(と v-leave-*)です。これらのクラス上で CSS のトランジションを定義しましょう。「v-」の接頭辞を「fade-」で置き換えるのが、name='fade' です。Transition がサポートするのは単一の子要素だけです — リストには、TransitionGroup を。

vue3
<template>
  <Transition name="fade">
    <p v-if="show">Hello</p>
  </Transition>
</template>

<style>
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>
07

リストレンダリング

配列での v-for

配列を反復し、各アイテムと(オプションで)インデックスを公開するのが、v-for です。item.id のような安定した一意の値に、常に :key をバインドしましょう — これにより、並べ替えの間、Vue が新旧のノードをマッチでき、コンポーネントの状態と DOM が効率的に保たれます。キーとしてのインデックスは、アイテムが挿入/削除/並べ替えられたとき壊れ、微妙なバグを引き起こします。

vue3
<script setup>
import { ref } from 'vue'
const items = ref([
  { id: 1, name: 'Apple' },
  { id: 2, name: 'Banana' },
  { id: 3, name: 'Cherry' }
])
</script>

<template>
  <!-- always provide :key with stable unique id -->
  <li v-for="item in items" :key="item.id">
    {{ item.name }}
  </li>

  <!-- with index (avoid as :key) -->
  <li v-for="(item, index) in items" :key="item.id">
    {{ index + 1 }}. {{ item.name }}
  </li>
</template>

オブジェクトと範囲での v-for

オブジェクト上の v-for は、デフォルトで値を反復します。第 2 引数がキーで、第 3 がインデックスです。Object.keys() に従うのが(文字列キーの挿入順)、オブジェクトの反復順です。数値 n 付きの v-for は、1 から n まで反復します(両端を含み、0 から n-1 ではありません)。フィルタやソートされたリストのためには、読みやすさとキャッシングのために、インラインのロジックでなく computed プロパティを優先しましょう。

vue3
<template>
  <!-- iterate object: (value, key, index) -->
  <div v-for="(value, key, index) in user" :key="key">
    {{ index }}. {{ key }}: {{ value }}
  </div>

  <!-- iterate a number range (1 to n inclusive) -->
  <span v-for="n in 10" :key="n">{{ n }} </span>
  <!-- 1 2 3 4 5 6 7 8 9 10 -->

  <!-- use v-for of computed for derived lists -->
  <li v-for="todo in doneTodos" :key="todo.id">
    {{ todo.text }}
  </li>
</template>

リストの変化の検出

Proxy ベースのリアクティビティを使うのが、Vue 3 です。そのため、push、pop、splice、sort、reverse での配列のミューテーションが、すべて更新をトリガーします — (Vue 2 と違い)特別な注意が不要です。配列全体の置き換え(items.value = newArray)も機能します。ref の value のセッターがリアクティビティをトリガーするからです。新しい配列を作るのが、filter/map です — 更新のため、代入し戻しましょう。

vue3
<script setup>
import { ref } from 'vue'

const items = ref([1, 2, 3])

// MUTATION methods (Vue 3 detects these via Proxy)
items.value.push(4)        // add
items.value.pop()          // remove last
items.value.splice(1, 1)   // remove at index
items.value.sort()         // sort

// REPLACEMENT (always reactive)
items.value = items.value.filter(n => n > 1)
items.value = [...items.value, 5]
</script>

リストのための TransitionGroup

v-for のリストをアニメーション化するのが、TransitionGroup です:enter、leave、そして move(アイテムが位置を変えるとき)です。Transition と違い、本物の要素を表示します(tag 経由で設定します)。各子には、一意の :key が必須です。リストが並べ替えられたとき、アイテムが新しい位置へスライドするのをアニメーション化するのが、.list-move クラスで — 素の CSS では達成できない、磨かれた効果です。滑らかな動きのためには、leave-active に position: absolute が必要です。

vue3
<template>
  <TransitionGroup name="list" tag="ul">
    <li v-for="item in items" :key="item.id">
      {{ item.text }}
    </li>
  </TransitionGroup>
</template>

<style>
.list-enter-active, .list-leave-active {
  transition: all 0.5s ease;
}
.list-enter-from, .list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}
/* animate items moving to new positions */
.list-move {
  transition: transform 0.5s ease;
}
</style>

パフォーマンス:v-memo

最適化のヒントであるのが、v-memo です。依存配列の値のいずれかが変わらない限り、Vue が要素の再レンダリングをスキップします。ほとんどのアイテムが各更新で変わらない大きなリストのためには、これが再レンダリングを劇的に減らせます。パフォーマンスの問題を計測したときだけ使いましょう — 早すぎる最適化は、複雑さと古い UI のリスクを加えます。

vue3
<template>
  <!-- skip re-render of this item unless 'id' or 'selected' changes -->
  <div
    v-for="item in hugeList"
    :key="item.id"
    v-memo="[item.id, item.id === selectedId]"
  >
    {{ item.name }} — {{ item.id === selectedId ? '★' : '' }}
  </div>
</template>
08

イベント処理

インラインのハンドラ

クリックハンドラをバインドするのが、@click(v-on:click の省略形)です。簡単なケースには、インラインの文(count++)が機能します。メソッド名(greet)は、自動的にネイティブイベントを最初の引数として受け取ります。カスタム引数とイベントの両方を渡すには、$event でメソッドを明示的に呼びましょう:greet('hi', $event) です。

vue3
<script setup>
import { ref } from 'vue'
const count = ref(0)
const name = ref('Vue')

function greet(event) {
  alert('Hello ' + name.value)
  // event is the native DOM event
  console.log(event.target.tagName)
}
</script>

<template>
  <!-- inline statement -->
  <button @click="count++">Add</button>

  <!-- method reference (auto-receives event) -->
  <button @click="greet">Greet</button>

  <!-- call with custom args (use $event for native event) -->
  <button @click="greet($event)">Greet</button>
</template>

イベントの修飾子

ドットでイベント名の後に連鎖するのが、イベントの修飾子です。最もよくあるのが、.prevent と .stop です(フォームの送信、イベントのバブリング)。要素自体(子でなく)がクリックされたときだけハンドラが発火するのを確保するのが、.self です。ハンドラが preventDefault を呼ばないとブラウザに伝え、より滑らかなスクロールを可能にするのが、.passive で — タッチ/スクロールのハンドラに重要です。

vue3
<template>
  <!-- .prevent: call preventDefault() -->
  <form @submit.prevent="onSubmit">...</form>

  <!-- .stop: call stopPropagation() -->
  <div @click="outer">
    <button @click.stop="inner">Won't bubble</button>
  </div>

  <!-- .self: only trigger if event.target === current element -->
  <div @click.self="onSelf">Only direct clicks</div>

  <!-- .once: handler removed after first invocation -->
  <button @click.once="init">Init once</button>

  <!-- .capture: use capture phase instead of bubble -->
  <div @click.capture="onCapture">...</div>

  <!-- .passive: improve scroll perf (no preventDefault) -->
  <div @scroll.passive="onScroll">...</div>
</template>

キーとシステムの修飾子

キー名によりキーボードイベントをフィルタするのが、キーの修飾子です(.enter、.esc、.delete、.space、.tab、.up、.down、.left、.right)。そのキーが押されていることを要求するのが、システムの修飾子(.ctrl、.alt、.shift、.meta)です。他のシステムの修飾子が押されていないことを確保するのが、.exact で — @click.ctrl.exact は、Ctrl+Shift+Click でなく、Ctrl+Click でのみ発火します。Vue がエイリアスしないキーには、kebab-case を使いましょう(page-down)。

vue3
<template>
  <!-- key modifiers: only fire on specific keys -->
  <input @keyup.enter="submit" />
  <input @keyup.esc="cancel" />
  <input @keyup.delete="remove" />

  <!-- system modifiers: ctrl, alt, shift, meta -->
  <button @click.ctrl="openInNewTab">Ctrl+Click</button>
  <input @keyup.alt.enter="altEnter" />

  <!-- .exact: no other modifiers can be pressed -->
  <button @click.ctrl.exact="onCtrlOnly">Ctrl only</button>

  <!-- any key code via kebab-case (deprecated but works) -->
  <input @keyup.page-down="onPageDown" />
</template>

emit によるカスタムイベント

子のコンポーネントが、上へ通信するためイベントを emit します。イベント名を宣言するのが、defineEmits です(検証と IDE のヒントに使われます)。親が @event-name で listen します。emit への追加の引数として渡され、親のハンドラが受け取るのが、ペイロードです。慣例では、テンプレートでは kebab-case のイベント名(my-event)、defineEmits では camelCase(myEvent)を使いましょう — Vue が自動変換します。

vue3
<!-- ChildButton.vue -->
<script setup>
const emit = defineEmits(['increment', 'delete'])

function onClick() {
  // emit with payload
  emit('increment', 1)
}
</script>

<template>
  <button @click="onClick">+1</button>
</template>

<!-- Parent.vue -->
<template>
  <ChildButton @increment="onIncrement" @delete="remove" />
</template>

<script setup>
function onIncrement(amount) {
  console.log('incremented by', amount)
}
</script>

コンポーネント上の v-model

コンポーネント上の双方向のバインディングのためのモダンな(Vue 3.4+)マクロであるのが、defineModel() です — 親の v-model と自動的に同期する ref を返します。複数のバインディングのためには、名前付きのモデルを使いましょう:v-model:fieldName です。内部では、「update:modelValue」(か「update:fieldName」)を emit し、親がバインドされた ref を同期します。古いコードは、defineProps + defineEmits を手動で使います。

vue3
<!-- CustomInput.vue -->
<script setup>
const model = defineModel()
</script>

<template>
  <input :value="model" @input="model = $event.target.value" />
</template>

<!-- Parent.vue -->
<template>
  <CustomInput v-model="text" />
</template>

<!-- multiple v-models (Vue 3.4+) -->
<template>
  <UserForm v-model:name="name" v-model:email="email" />
</template>
09

フォームのバインディング

Text と Textarea

テキスト入力上の v-model は、毎 input イベントで同期します。textarea のためには、(:value としてでなく)要素に直接 v-model を置きましょう — 属性内の複数行のコンテンツは機能しません。修飾子:blur/change で同期し更新を減らすのが、.lazy、空白を剥ぎ取るのが、.trim、値を Number へキャストするのが、.number です。修飾子を連鎖させましょう:v-model.lazy.trim です。

vue3
<script setup>
import { ref } from 'vue'
const text = ref('')
const message = ref('')
</script>

<template>
  <!-- text input: binds on every keystroke -->
  <input v-model="text" placeholder="Type here" />
  <p>You typed: {{ text }}</p>

  <!-- textarea: insert tags inside, not :value -->
  <textarea v-model="message" rows="4"></textarea>
  <p>Preview: {{ message }}</p>

  <!-- .lazy: sync on 'change' (blur) instead of 'input' -->
  <input v-model.lazy="text" />

  <!-- .trim: strip leading/trailing whitespace -->
  <input v-model.trim="text" />

  <!-- .number: cast to Number (NaN if invalid) -->
  <input v-model.number="age" type="number" />
</template>

Checkbox と Radio

ブールにバインドされるのが(checked = true)、単一のチェックボックスです。同じ v-model を共有する複数のチェックボックスが、それらの value 属性の配列にバインドします — チェックすると値が加わり、外すと取り除かれます。選ばれたオプションの値が ref にバインドされるのが、v-model を共有するラジオボタンです。ブールのマッピングをカスタマイズするには、true-value / false-value の属性を使いましょう。

vue3
<script setup>
import { ref } from 'vue'
const agreed = ref(false)
const fruits = ref([])     // array for multi-checkbox
const picked = ref('')     // string for radio
</script>

<template>
  <!-- single checkbox -> boolean -->
  <input type="checkbox" v-model="agreed" /> I agree

  <!-- multiple checkboxes with same v-model -> array -->
  <input type="checkbox" value="apple" v-model="fruits" /> Apple
  <input type="checkbox" value="banana" v-model="fruits" /> Banana
  <input type="checkbox" value="cherry" v-model="fruits" /> Cherry
  <p>Selected: {{ fruits }}</p>

  <!-- radio: value binds to the chosen option -->
  <input type="radio" value="A" v-model="picked" /> A
  <input type="radio" value="B" v-model="picked" /> B
</template>

Select

<select> 上では、(options でなく)select 要素に v-model が行き、選ばれたオプションの value と同期します。「please select」の UX のためには、空の値付きの無効なプレースホルダーのオプションを使いましょう。動的なオプションのためには、v-for で表示し、:value をバインドしましょう。複数選択を許可するのが、multiple の属性で — その後、v-model が選択された値の配列にバインドします。

vue3
<script setup>
import { ref } from 'vue'
const selected = ref('')
const multi = ref([])

const options = [
  { value: 'a', label: 'Option A' },
  { value: 'b', label: 'Option B' }
]
</script>

<template>
  <!-- single select -->
  <select v-model="selected">
    <option disabled value="">Please select</option>
    <option value="a">A</option>
    <option value="b">B</option>
  </select>

  <!-- dynamic options -->
  <select v-model="selected">
    <option v-for="opt in options" :key="opt.value" :value="opt.value">
      {{ opt.label }}
    </option>
  </select>

  <!-- multi-select (hold Ctrl/Cmd) -> array -->
  <select v-model="multi" multiple>
    <option value="x">X</option>
    <option value="y">Y</option>
  </select>
</template>

フォームの送信とバリデーション

デフォルトのページのリロードを防ぎながら、フォームの送信を扱うのが、@submit.prevent です。関連するフィールドをグループ化するのが、リアクティブなフォームオブジェクトです。バリデーションのためには、複雑なフォームには、VeeValidate や Zod + composable のようなライブラリが人気ですが、小さいフォームには、errors オブジェクトを返す簡単な validate() 関数がよく機能します。SPA スタイルの送信を可能にするため、常に prevent default しましょう。

vue3
<script setup>
import { reactive, ref } from 'vue'

const form = reactive({
  email: '',
  password: ''
})
const errors = ref({})

function validate() {
  errors.value = {}
  if (!form.email.includes('@')) errors.value.email = 'Invalid email'
  if (form.password.length < 6) errors.value.password = 'Too short'
  return Object.keys(errors.value).length === 0
}

function onSubmit() {
  if (!validate()) return
  // submit form...
}
</script>

<template>
  <form @submit.prevent="onSubmit">
    <input v-model.trim="form.email" />
    <span v-if="errors.email">{{ errors.email }}</span>

    <input type="password" v-model="form.password" />
    <span v-if="errors.password">{{ errors.password }}</span>

    <button type="submit">Submit</button>
  </form>
</template>

カスタムコンポーネントでの v-model

再利用のために、フォームのフィールドをカスタムコンポーネントで包みましょう。親の値を読み、「update:modelValue」の emit 経由で書き戻す ref を返すのが、defineModel() です。コンポーネントがモデルへ :value をバインドし、@input が更新します。このパターンにより、ネイティブの要素と同じように v-model で使える、一貫したデザインシステムのフォーム入力(BaseInput、BaseSelect、BaseCheckbox)を構築できます。

vue3
<!-- BaseInput.vue -->
<script setup>
const model = defineModel()

defineProps({
  label: String,
  type: { type: String, default: 'text' }
})
</script>

<template>
  <label>
    {{ label }}
    <input
      :type="type"
      :value="model"
      @input="model = $event.target.value"
    />
  </label>
</template>

<!-- Usage -->
<template>
  <BaseInput v-model="email" label="Email" type="email" />
</template>
10

コンポーネント

コンポーネントの定義と使用

template、script、オプションの style を持つ .vue ファイルであるのが、コンポーネントです。(<script setup> でローカルに自動登録され)インポートし、カスタムの HTML タグとして使いましょう。コンポーネント名は、script では PascalCase で、テンプレートでは kebab-case(my-button)であり得ます — Vue が正規化します。どこでもインポートなしで利用可能なのが、グローバルに登録されたコンポーネント(app.component)です。

vue3
<!-- MyButton.vue -->
<template>
  <button class="btn"><slot /></button>
</template>

<!-- App.vue -->
<script setup>
import MyButton from './MyButton.vue'
</script>

<template>
  <MyButton>Click me</MyButton>
</template>

動的なコンポーネント

コンポーネントを動的に表示するのが、<component :is='...'> です — 値は、登録された名前の文字列、インポートされたコンポーネントオブジェクト、defineAsyncComponent であり得ます。タブの間で切り替えるとき、コンポーネントの状態(フォームの入力、スクロール位置)を保存するには、<keep-alive> で包みましょう。深いリアクティビティのオーバーヘッドを避けるため、コンポーネントオブジェクトには、(ref でなく)shallowRef を使いましょう。

vue3
<script setup>
import { ref, shallowRef } from 'vue'
import HomeTab from './HomeTab.vue'
import PostsTab from './PostsTab.vue'
import ArchiveTab from './ArchiveTab.vue'

const tabs = { HomeTab, PostsTab, ArchiveTab }
const current = shallowRef('HomeTab')

// keep component state when switching (e.g. form input)
import { keep-alive } from 'vue' // not real — use the tag
</script>

<template>
  <button v-for="(comp, name) in tabs" :key="name" @click="current = name">
    {{ name }}
  </button>

  <keep-alive>
    <component :is="tabs[current]" />
  </keep-alive>
</template>

非同期のコンポーネント

最初のレンダリングでコンポーネントを遅延ロードするのが、defineAsyncComponent です — チャンクがオンデマンドで取得され、初期のバンドルサイズが減ります。滑らかな UX のために、ローディング/エラーの状態を設定しましょう。複数の非同期のコンポーネントを調整するには、Suspense と組み合わせましょう。コンポーネントのモジュールの Promise を返すのが、ローダーです(動的な import() に基づき、Vite/Webpack が自動的に分割します)。

vue3
<script setup>
import { defineAsyncComponent } from 'vue'

// lazy-load on first use (code-split)
const HeavyChart = defineAsyncComponent(() =>
  import('./HeavyChart.vue')
)

// with loading, error, delay, timeout states
const AdminPanel = defineAsyncComponent({
  loader: () => import('./AdminPanel.vue'),
  loadingComponent: LoadingSpinner,
  errorComponent: ErrorMsg,
  delay: 200,        // show loading after 200ms
  timeout: 5000      // error if not loaded in 5s
})
</script>

<template>
  <HeavyChart />
  <AdminPanel />
</template>

コンポーネントの v-model(複数)

単一のコンポーネントに複数の双方向のバインディングを公開させてくれるのが、名前付きのモデルです。それぞれを宣言するのが、defineModel('name') です。親が、v-model:name='...' を使います。複数のフィールドを束ねるフォームコンポーネントに最適です(例:street、city、zip を持つアドレスのコンポーネント)。デフォルトの v-model(名前なし)が、「modelValue」へマッピングします。

vue3
<!-- UserForm.vue -->
<script setup>
const firstName = defineModel('firstName')
const lastName = defineModel('lastName')
</script>

<template>
  <input v-model="firstName" />
  <input v-model="lastName" />
</template>

<!-- Parent.vue -->
<template>
  <UserForm
    v-model:firstName="form.first"
    v-model:lastName="form.last"
  />
</template>

再帰と循環のコンポーネント

コンポーネントは、自身のファイル名で(自動自己参照)自身を参照できます。ツリー構造(ファイルツリー、コメントスレッド、メニュー)に最適です。2 つのコンポーネントの間の循環参照のためには(A が B をインポートし、B が A をインポートします)、どちらかに defineAsyncComponent を使うか、beforeCreate でインポートしましょう。再帰的なコンポーネントを Vue は扱いますが、無限ループに注意しましょう — 必ず基底ケース(子なし)を持ちましょう。

vue3
<!-- TreeNode.vue -->
<script setup>
defineProps({
  node: Object
})

// a component can reference itself by its filename
// TreeNode.vue can use <TreeNode /> recursively
</script>

<template>
  <div>
    {{ node.label }}
    <ul v-if="node.children?.length">
      <li v-for="child in node.children" :key="child.id">
        <TreeNode :node="child" />
      </li>
    </ul>
  </div>
</template>
11

Props

Props の宣言

コンポーネントの入力の契約を宣言するのが、defineProps です。実行時の宣言が、type、default、required、validator をサポートします。Vue 3 の型ベースの宣言(TS のみ)が、型の安全性を与えますが、実行時の検証が失われます(volar + バリデータのライブラリと共に使いましょう)。オブジェクト/配列のデフォルトは、ファクトリ関数を使わなければなりません:default: () => [] です。

vue3
<script setup>
// runtime declaration (validates types)
const props = defineProps({
  title: String,
  count: { type: Number, default: 0 },
  items: { type: Array, required: true },
  callback: { type: Function, default: () => {} },
  status: {
    type: String,
    validator: (v) => ['active', 'idle'].includes(v)
  }
})

// type-based declaration (TS only, no runtime validation)
const props2 = defineProps<{
  title: string
  count?: number
}>()
</script>

Prop の命名と渡し

Props は、JS では camelCase(greetingMessage)で、テンプレートでは kebab-case(greeting-message)であるべきです — HTML は大文字小文字を区別しないため、kebab-case がより安全です。Vue が両者の間を自動変換します。静的な文字列の props は素の属性の構文を使い、動的な値は :prop を使います。文字列として扱われないよう、数値/ブール/オブジェクトは常に : 付きで渡しましょう。

vue3
<!-- Child.vue -->
<script setup>
defineProps({
  greetingMessage: String,
  userId: Number
})
</script>

<!-- Parent.vue -->
<template>
  <!-- kebab-case in templates (HTML-friendly) -->
  <Child greeting-message="Hello" :user-id="42" />

  <!-- camelCase also works in SFC templates -->
  <Child greetingMessage="Hello" :userId="42" />
</template>

一方向のデータフロー

Props は読み取り専用です — 直接ミューテートしてはいけません。開発モードで Vue が警告します。prop の値を変えるには、イベントを emit し、親に更新させましょう(一方向のデータフローです)。ローカルの作業コピーのためには、prop から ref を初期化し、watch で同期しましょう。最もきれいな双方向のパターンであるのが、emit と更新のダンスを抽象化する、defineModel での v-model です。

vue3
<!-- BAD: mutating a prop -->
<script setup>
const props = defineProps(['count'])

function inc() {
  props.count++  // WARNING: don't mutate props!
}
</script>

<!-- GOOD: emit to parent, or use local copy -->
<script setup>
import { ref, watch } from 'vue'
const props = defineProps(['count'])
const emit = defineEmits(['update:count'])

// local copy that syncs with prop
const local = ref(props.count)
watch(() => props.count, v => local.value = v)

function inc() {
  local.value++
  emit('update:count', local.value)
}
</script>

Prop の検証とデフォルト

開発モードで props を検証し、失敗で警告するのが、Vue です(本番ではしません)。type は、コンストラクタ(String、Number、Boolean、Array、Object、Function、Symbol)か、それらの配列を受け付けます。オブジェクトと配列のデフォルトは、新しいインスタンスを返す関数でなければなりません — さもなければ、すべてのコンポーネントが同じデフォルトの参照を共有します(ミューテーションのバグです)。型のチェックの後に走るのが、バリデータです。

vue3
<script setup>
const props = defineProps({
  // type can be an array of allowed types
  value: { type: [String, Number], required: true },

  // object/array default MUST be a factory function
  list: {
    type: Array,
    default: () => []
  },

  // custom validator
  age: {
    type: Number,
    validator: (v) => v >= 0 && v <= 150
  },

  // multiple checks combined
  email: {
    type: String,
    required: true,
    validator: (v) => v.includes('@')
  }
})
</script>

ブールのキャストと属性のフォールスルー

ブールの props には特別なキャスティングがあります:値なしの存在が true を意味します。非 prop の属性(class、style、id、data-*)を自動的にルート要素へ渡すのが、属性のフォールスルーです。複数のルートは、望まれる要素上の明示的な v-bind='$attrs' を要求します。完全な制御のためには、defineOptions({ inheritAttrs: false }) でフォールスルーを無効化しましょう。

vue3
<!-- prop declared as Boolean -->
<script setup>
defineProps({
  disabled: Boolean,
  active: Boolean
})
</script>

<!-- Parent -->
<template>
  <MyButton disabled />       <!-- disabled = true -->
  <MyButton :disabled="false" /> <!-- disabled = false -->
  <MyButton />                <!-- disabled = undefined -->
</template>

<!-- Attribute fallthrough: non-prop attributes
     land on the root element automatically -->
<template>
  <!-- <MyButton data-id="5" class="large" /> -->
  <!-- the data-id and class merge onto the <button> root -->
  <button>...</button>
</template>
12

Emits

宣言と Emit

コンポーネントが emit できるイベントを宣言するのが、defineEmits です。オブジェクトの形式は、ペイロードを受け取り、(開発モードで)警告するために false を返す、バリデータを可能にします。Emits はツリーを上へ行き — 親が @event-name で listen します。常に emits を明示的に宣言しましょう:API を文書化し、attr のフォールスルーの除外を可能にし、検証をサポートします。emit() が、イベント名とオプションのペイロードの引数を取ります。

vue3
<script setup>
// declare emits (with optional validation)
const emit = defineEmits({
  // null-ish = no validation
  click: null,

  // function = validate payload
  submit: (payload) => {
    if (!payload.email) {
      console.warn('submit needs email')
      return false
    }
    return true
  }
})

function handleSubmit() {
  emit('submit', { email: '[email protected]', name: 'Alice' })
}
</script>

Emits の Listen

親が @event-name(か v-on:event-name)で listen します。emit された任意のペイロードを、ハンドラが受け取ります。簡単な変換に便利なのが、インラインの矢印関数です(@increment='n => count += n')。メソッドのハンドラは、自動的に最初の引数としてペイロードを受け取ります。emits で宣言されない限り、コンポーネントのルート要素上のネイティブの DOM イベントがフォールスルーします — 「click」を宣言すると、代わりにカスタムイベントになります。

vue3
<!-- Child.vue -->
<script setup>
const emit = defineEmits(['increment', 'delete'])

function click() {
  emit('increment', 5)
}
</script>

<template>
  <button @click="click">+5</button>
</template>

<!-- Parent.vue -->
<template>
  <!-- inline handler -->
  <Child @increment="n => count += n" />

  <!-- method handler -->
  <Child @increment="onIncrement" @delete="onDelete" />
</template>

<script setup>
function onIncrement(amount) {
  console.log('incremented by', amount)
}
</script>

v-model の実装

コンポーネント上の v-model は、:modelValue + @update:modelValue の糖衣です。子が modelValue の prop 経由で値を受け取り、同期するために update:modelValue を emit します。手動のパターンがこれで、defineModel()(Vue 3.4+)がそれを包みます。名前付きの v-model(v-model:foo)のためには、prop 名が foo で、イベントが update:foo です。ネイティブの入力のように機能するフォームコンポーネントの構築を可能にするのが、これです。

vue3
<!-- CustomInput.vue (manual implementation) -->
<script setup>
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])

function onInput(e) {
  emit('update:modelValue', e.target.value)
}
</script>

<template>
  <input
    :value="modelValue"
    @input="onInput"
  />
</template>

<!-- Parent -->
<template>
  <CustomInput v-model="text" />
</template>

Emit の検証

Emit のバリデータは、ペイロードの引数を受け取り、開発モードの警告を引き起こすため false を返します。emit を防ぐのではなく、警告するだけです。開発の早い段階で契約の違反を捉えます。期待されるペイロードの shape を文書化するために使いましょう。本番では、バリデータは剥ぎ取られるため、セキュリティや制御フローに頼ってはいけません。

vue3
<script setup>
const emit = defineEmits({
  // no validation
  click: null,

  // validate payload; return false to warn
  change: (value) => {
    if (typeof value !== 'string') {
      console.warn('change payload must be string')
      return false
    }
    return true
  },

  // validate multiple args
  update: (id, value) => {
    if (!id || value === undefined) return false
    return true
  }
})

// validation runs on emit
emit('change', 123)  // warns: must be string
</script>

Events 対 Props:いつ何を使うか

一方向のデータフローに従いましょう:下へ props、上へ events です。双方向のバインディングのためには、v-model(props + emit の糖衣)を使いましょう。深くネストした通信のためには、props-drilling が苦痛になり — 依存の注入のためには provide/inject を、共有状態のためにはストア(Pinia)を使いましょう。イベントは「何かが起きた」の通知のためのもので、props は「これがあなたのデータです」のためのものです。

vue3
<!-- Parent-to-child: props (down) -->
<template>
  <Child :data="parentData" :config="config" />
</template>

<!-- Child-to-parent: emits (up) -->
<template>
  <Child @change="onChange" @submit="onSubmit" />
</template>

<!-- Two-way: v-model (combines both) -->
<template>
  <Child v-model="value" />
</template>

<!-- For complex state, prefer provide/inject or a store -->
13

Slots

デフォルトのスロット

親が、子のコンポーネントのテンプレートへコンテンツを注入させてくれるのが、slots です。プレースホルダーであるのが、<slot> 要素です。親の子のコンテンツが、デフォルトのスロットを満たします。合成を可能にするのが、slots です:Card がラッパーのスタイリングを扱い、親が内側のコンテンツを制御します。slots がなければ、考えられるすべての内側の要素のための prop が必要になります — slots はずっと柔軟です。

vue3
<!-- Card.vue -->
<template>
  <div class="card">
    <slot />
  </div>
</template>

<!-- Usage -->
<template>
  <Card>
    <p>This goes into the default slot</p>
    <button>Action</button>
  </Card>
</template>

名前付きのスロット

コンポーネントに複数のコンテンツのプレースホルダーを持たせてくれるのが、名前付きの slots です。<slot name='foo' /> で宣言し、<template #foo> で満たしましょう。v-slot: の省略形が、# です。名前のないスロットが「default」のスロットです — template のラッパーなしのコンテンツがそこへ行きます。親が各領域を満たすレイアウト(header、sidebar、main、footer)に最適なのが、名前付きの slots です。

vue3
<!-- Layout.vue -->
<template>
  <header><slot name="header" /></header>
  <main><slot /></main>
  <footer><slot name="footer" /></footer>
</template>

<!-- Usage with # shorthand -->
<template>
  <Layout>
    <template #header>
      <h1>My Page Title</h1>
    </template>

    <!-- default slot (no #name) -->
    <p>Main content here</p>

    <template #footer>
      <p>© 2025</p>
    </template>
  </Layout>
</template>

Slot Props(スコープ付きスロット)

子が親のスロットのコンテンツへデータを渡し戻させてくれるのが、スコープ付きの slots です。子が <slot :item='item'> にデータをバインドし、親が v-slot='{ item }'(か #default='{ item }')経由で受け取ります。再利用可能なリストコンポーネント(データテーブル、仮想リスト)の基礎がこれです:子が反復を扱い、親が各アイテムのレンダリングを制御します。

vue3
<!-- List.vue -->
<template>
  <ul>
    <li v-for="item in items" :key="item.id">
      <slot :item="item" :index="index" />
    </li>
  </ul>
</template>

<script setup>
defineProps(['items'])
</script>

<!-- Usage: receive slot props via v-slot -->
<template>
  <List :items="todos">
    <template #default="{ item, index }">
      <input type="checkbox" v-model="item.done" />
      <span :class="{ done: item.done }">{{ index }}: {{ item.text }}</span>
    </template>
  </List>
</template>

デフォルトのスロットのコンテンツ

<slot> と </slot> の間に置かれるのが、スロットのフォールバックのコンテンツです。親がスロットのコンテンツを提供しないときだけ表示されます。賢明なデフォルトに最適です — ボタンのラベル、空の状態のメッセージ、プレースホルダーです。親が空の文字列さえ渡せば、フォールバックが上書きされます。

vue3
<!-- Button.vue -->
<template>
  <button>
    <slot>Click here</slot>  <!-- fallback content -->
  </button>
</template>

<!-- Usage -->
<template>
  <Button />             <!-- renders "Click here" -->
  <Button>Save</Button>  <!-- renders "Save" -->
</template>

レンダリングスコープとスロットの使用

スロットのコンテンツは、PARENT のスコープで表示されます — 親の状態へアクセスできますが、(slot props 経由でなければ)子の状態へは直接アクセスできません。この分離により、子が(ページネーション、仮想化、フェッチの)メカニズムを扱い、親がプレゼンテーションを制御できます。スコープ付きスロットのパターン(FancyList + UserCard)が、強力な合成の技法です — 子がデータフローを所有し、親がレンダリングを所有します。

vue3
<!-- FancyList.vue (scoped slot pattern) -->
<script setup>
const props = defineProps(['items', 'pageSize'])
import { ref, computed } from 'vue'

const page = ref(1)
const paged = computed(() =>
  props.items.slice((page.value - 1) * props.pageSize, page.value * props.pageSize)
)
</script>

<template>
  <div v-for="item in paged" :key="item.id">
    <slot :item="item" :page="page" />
  </div>
</template>

<!-- Usage: parent fully controls rendering -->
<FancyList :items="users" :pageSize="10">
  <template #default="{ item, page }">
    <UserCard :user="item" />
    <small>Page {{ page }}</small>
  </template>
</FancyList>
14

ライフサイクルのフック

Composition API のフック

特定のステージで走るのが、ライフサイクルのフックです。DOM がレンダリングされた後に発火するのが、onMounted です(要素へのアクセス、canvas ライブラリの実行、データのフェッチが安全です)。すべてのリアクティブな更新の後に発火するのが、onUpdated です — ここで状態をミューテートすることは避けましょう(無限ループです)。クリーンアップのためのものが、onUnmounted です(タイマー、リスナー、購読)。フックは、setup で同期的に呼ばれなければなりませんが、複数回呼べます。

vue3
<script setup>
import {
  onBeforeMount, onMounted,
  onBeforeUpdate, onUpdated,
  onBeforeUnmount, onUnmounted,
  onActivated, onDeactivated,
  onErrorCaptured
} from 'vue'

onBeforeMount(() => console.log('before mount'))
onMounted(() => console.log('mounted — DOM ready'))
onBeforeUpdate(() => console.log('before re-render'))
onUpdated(() => console.log('after re-render'))
onBeforeUnmount(() => console.log('before unmount'))
onUnmounted(() => console.log('unmounted — cleanup'))
</script>

Setup 対 Created

<script setup> では、スクリプトの本体全体が、コンポーネントの初期化の間に走ります — Options API の beforeCreate + created に相当します。別の created() フックはありません。インスタンスごとに一度走るのが、トップレベルのコードです(宣言、関数の呼び出し、async の作業さえ)。データのフェッチのために、これはよくある開始の場所です(onMounted でも構いません — どちらでも同じようにフェッチが始まります)。

vue3
<script setup>
// <script setup> runs BEFORE the component is mounted
// (equivalent to beforeCreate + created in Options API)

import { ref } from 'vue'

// this code runs once per component instance,
// before reactive state is exposed to the template
const count = ref(0)
console.log('component created, count =', count.value)

// no need for created() hook — just run code here
fetch('/api/data')
  .then(r => r.json())
  .then(data => { /* ... */ })
</script>

Mounted とクリーンアップ

setup/クリーンアップのペアが不可欠です:onMounted で加えられたすべてのリスナー、タイマー、購読、オブザーバーは、onUnmounted で取り除かれなければなりません。クリーンアップの失敗は、メモリリークと、破壊されたコンポーネントで発火するゾンビハンドラを引き起こします。パターン:onMounted での addEventListener、onUnmounted での removeEventListener です。ウォッチャーのためには、返された stop 関数を使うか、アンマウントで自動的にクリーンします。

vue3
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const windowWidth = ref(window.innerWidth)

function onResize() {
  windowWidth.value = window.innerWidth
}

onMounted(() => {
  // setup side effects after DOM is ready
  window.addEventListener('resize', onResize)
  console.log('mounted')
})

onUnmounted(() => {
  // ALWAYS clean up to avoid memory leaks
  window.removeEventListener('resize', onResize)
})
</script>

KeepAlive のフック

コンポーネントが <KeepAlive> で包まれると、離れることはアンマウントになりません — 非アクティブ化(キャッシュ)されます。表示/非表示で発火するのが、onActivated と onDeactivated です。完全な setup/teardown なしで、(ポーリング、ビデオ再生の)作業を一時停止/再開するのに使いましょう。onMounted は(最初のアクティベーションで)まだ一度発火し、キャッシュされている間、onUnmounted は決して発火しません。キャッシュされたタブのためのリソース使用の最適化をさせてくれるのが、これらのフックです。

vue3
<script setup>
import { onActivated, onDeactivated } from 'vue'

// these fire when the component is wrapped in <KeepAlive>
// and is being shown (activated) or hidden (deactivated)
onActivated(() => {
  console.log('component shown again — resume polling')
  startPolling()
})

onDeactivated(() => {
  console.log('component hidden but not unmounted — pause')
  stopPolling()
})

// onMounted fires only once (first show)
// onActivated fires every time it's re-shown
</script>

Error Captured

子孫のコンポーネントからのエラー(テンプレート、レンダリング、ライフサイクル、ウォッチャー内)を捉えるのが、onErrorCaptured です。(error, instance, info) を受け取ります。false を返すと、親の errorCaptured のハンドラとグローバルの errorHandler への伝播が止まります。子のエラーを優雅に扱う境界のコンポーネントのためのものです(React の Error Boundaries のように)。非同期のエラーの状態のために、Suspense と組み合わせましょう。

vue3
<script setup>
import { onErrorCaptured, ref } from 'vue'

const error = ref(null)

onErrorCaptured((err, instance, info) => {
  // err: the error thrown
  // instance: component that threw
  // info: lifecycle hook or event name where it occurred
  error.value = err.message
  console.error('Captured:', err, info)

  // return false to stop propagation to parent
  return false
})
</script>

<template>
  <div v-if="error" class="error">{{ error }}</div>
  <slot v-else />
</template>
15

Composition API

ref 対 reactive

任意の値(プリミティブ、オブジェクト)で機能するのが、ref() です。JS でのリアクティブなアクセスには .value が必要ですが、テンプレートでは自動的にアンラップされます。オブジェクト/配列でのみ機能するのが、reactive() で — .value が不要です。プリミティブと置き換え可能な値には ref を、グループ化された状態には reactive を使いましょう。経験則:個々の値には ref() を、状態のオブジェクトには reactive() を優先しましょう。混ぜるのは構いません — refs はリアクティブなオブジェクトの内側で自動的にアンラップします。

vue3
<script setup>
import { ref, reactive } from 'vue'

// ref: works with any value, access via .value
const count = ref(0)
count.value++
console.log(count.value)  // 1

// reactive: only for objects/arrays, no .value needed
const state = reactive({ count: 0, user: { name: 'A' } })
state.count++
console.log(state.count)  // 1

// refs auto-unwrap in templates and reactive objects
const wrapper = reactive({ count })  // wrapper.count === count.value
</script>

reactive の落とし穴

reactive オブジェクトには、2 つの落とし穴があります:変数の再代入ができず(state = newObj)、代わりにプロパティをミューテートしましょう(state.list = [])。分解された変数がスナップショットであるため、分割代入がリアクティビティを失います。リンクされたままの refs へリアクティブなプロパティを変換するのが、toRefs() です。多くの開発者が ref() を優先する理由が、これらの落とし穴です — 置き換え可能(.value を設定するだけ)で、分解にも優しいです。

vue3
<script setup>
import { reactive, ref } from 'vue'

const state = reactive({ list: [1, 2, 3] })

// PITFALL 1: replacing the whole object loses reactivity
// state = reactive({ list: [4, 5] })  // ERROR: reassign

// GOOD: mutate properties
state.list = [4, 5]

// PITFALL 2: destructuring loses reactivity
let { list } = state  // 'list' is now plain
// list.push(4) won't trigger updates

// FIX: use toRefs to keep reactivity
import { toRefs } from 'vue'
const { list } = toRefs(state)  // now list is a ref
</script>

toRef と toRefs

リンクされたままの ref へ単一のリアクティブなプロパティを変換するのが、toRef() です(どちらかをミューテートすると、他方が影響されます)。すべてのプロパティを変換するのが、toRefs() で、分解を保ちながら、composables からリアクティブな状態を返すのに有用です。toRefs なしでは、分解された値がリアクティビティを失います。パターン:composable が toRefs(state) を返すことで、消費者がリアクティビティを壊さずに分解できます。

vue3
<script setup>
import { reactive, toRef, toRefs } from 'vue'

const state = reactive({
  count: 0,
  name: 'Alice'
})

// toRef: single property -> ref (stays linked to state)
const countRef = toRef(state, 'count')

// toRefs: all properties -> object of refs
const { count, name } = toRefs(state)

countRef.value++      // updates state.count
count.value++         // also updates state.count
console.log(state.count)  // 2
</script>

Setup での computed と watch

<script setup> では、computed() と watch() がインポートされ、直接呼ばれます。派生の ref を作るのが、computed で、ソースの変化でコールバックを走らせるのが、watch です。watch が取れるもの:単一の ref、ゲッター、ソースの配列、リアクティブなオブジェクトです。Composition API のコアのプリミティブがこれらであり、composables でロジックをカプセル化するために組み合わせましょう。

vue3
<script setup>
import { ref, computed, watch } from 'vue'

const a = ref(1)
const b = ref(2)

// computed: derived value, cached
const sum = computed(() => a.value + b.value)

// watch: side effect on change
watch(sum, (newSum) => {
  console.log('sum changed to', newSum)
})

// watch multiple sources
watch([a, b], ([newA, newB]) => {
  console.log('a or b changed:', newA, newB)
})
</script>

shallowRef と shallowReactive

深いリアクティビティから脱するのが、shallowRef と shallowReactive です — トップレベルの参照/プロパティだけが追跡されます。深い追跡が浪費される、大きなデータ構造(例:チャートのデータ配列、3D シーンのグラフ)のパフォーマンスを劇的に改善します。深いミューテーションの後に手動で Vue に通知するのが、triggerRef() です。パフォーマンスの問題を計測したときだけ、これらに手を伸ばしましょう。

vue3
<script setup>
import { shallowRef, shallowReactive, triggerRef } from 'vue'

// shallowRef: only .value changes trigger updates
// (deep changes to .value properties do NOT)
const big = shallowRef({ items: [1, 2, 3] })
big.value.items.push(4)       // NO update triggered
big.value = { items: [1,2,3,4] }  // update triggered

// force update after deep mutation
big.value.items.push(5)
triggerRef(big)  // tells Vue to re-render

// shallowReactive: only root-level props are reactive
const state = shallowReactive({ user: { name: 'A' } })
state.count = 1            // reactive
state.user.name = 'B'      // NOT reactive
</script>
16

Composables

Composable を書く

再利用可能なリアクティブなロジックをカプセル化する関数であるのが、composable です。慣例では、useSomething と名付けましょう。消費するコンポーネントのライフサイクルにバインドされる、Composition API のフック(onMounted など)を使います。refs とメソッドを返し、コンポーネントがそれらを分解します。React の hooks の Vue 相当物であるのが、composables です — render props や HOC なしで、ステートフルなロジックを共有させてくれます。

vue3
<!-- useMousePosition.js -->
import { ref, onMounted, onUnmounted } from 'vue'

export function useMousePosition() {
  const x = ref(0)
  const y = ref(0)

  function update(e) {
    x.value = e.pageX
    y.value = e.pageY
  }

  onMounted(() => window.addEventListener('mousemove', update))
  onUnmounted(() => window.removeEventListener('mousemove', update))

  return { x, y }
}

<!-- In component -->
<script setup>
import { useMousePosition } from './useMousePosition'
const { x, y } = useMousePosition()
</script>

ステートフルな Composable(共有状態)

状態が(関数の外の)モジュールスコープで宣言されると、シングルトンになります — composable を使うすべてのコンポーネントが、同じ状態を共有します。簡単なグローバル状態のための、Pinia の軽量な代替が、これです。直接のミューテーションを許さずに状態を公開するのが、readonly() で — 変更するには、コンポーネントが login/logout を呼ばなければなりません。複雑なアプリには、Pinia を優先しましょう(より良い devtools、永続化、SSR の対応)。

vue3
<!-- useUser.js -->
import { reactive, readonly } from 'vue'

// module-scoped state — shared across all consumers
const state = reactive({
  user: null,
  loading: false
})

export function useUser() {
  async function login(credentials) {
    state.loading = true
    state.user = await fetch('/api/login', {
      method: 'POST',
      body: JSON.stringify(credentials)
    }).then(r => r.json())
    state.loading = false
  }

  function logout() {
    state.user = null
  }

  return {
    user: readonly(state.user),  // expose read-only
    loading: readonly(state.loading),
    login,
    logout
  }
}

useFetch Composable

loading/error の状態で fetch を包み、リアクティブな url が変わると再フェッチするのが、この composable です。入力が ref かチェックするのが、isRef() で、アンラップするのが、unref() です(refs には値を返し、さもなければ同一性です)。消費者が手動で再フェッチできるよう、refresh を返しましょう。データフェッチのための composables の基本パターンが、(リアクティブな入力 + 自動再実行 + 状態の公開)これです。

vue3
<!-- useFetch.js -->
import { ref, watchEffect, isRef, unref } from 'vue'

export function useFetch(url) {
  const data = ref(null)
  const error = ref(null)
  const loading = ref(true)

  async function doFetch() {
    loading.value = true
    error.value = null
    try {
      const res = await fetch(unref(url))
      if (!res.ok) throw new Error('HTTP ' + res.status)
      data.value = await res.json()
    } catch (e) {
      error.value = e.message
    } finally {
      loading.value = false
    }
  }

  // re-fetch when url ref changes
  if (isRef(url)) {
    watchEffect(doFetch)
  } else {
    doFetch()
  }

  return { data, error, loading, refresh: doFetch }
}

クリーンアップ付きの Composable

副作用を登録する composables(リスナー、タイマー、購読)は、クリーンアップしなければなりません — 通常、composable の内側の onUnmounted 経由です。これは、composable を消費するコンポーネントにクリーンアップをバインドするため、消費者が覚える必要がありません。ユーティリティ関数より composables の大きな利点が、これです:コンポーネントのライフサイクルに参加するのです。

vue3
<!-- useEventListener.js -->
import { onUnmounted } from 'vue'

export function useEventListener(target, event, callback) {
  target.addEventListener(event, callback)

  // auto-cleanup when the consuming component unmounts
  onUnmounted(() => {
    target.removeEventListener(event, callback)
  })
}

<!-- Usage -->
<script setup>
import { useEventListener } from './useEventListener'
import { ref } from 'vue'

const key = ref('')
useEventListener(window, 'keydown', (e) => {
  key.value = e.key
})
// listener is removed automatically on unmount
</script>

Composable の規約

この規約に従いましょう:(1) composables に use 接頭辞で名付ける;(2) refs を返す(素の値ではなく — 素の値はリアクティビティを失います);(3) 柔軟性のために、入力として refs かゲッターを受け付ける;(4) クリーンアップには onUnmounted を使う;(5) 焦点を保つ(composable ごとに 1 つの関心事)です。これらの規約により、composables が互いに合成可能で、使用が予測可能になります。

vue3
<!-- DO: name with 'use' prefix, return refs -->
export function useCounter(initial = 0) {
  const count = ref(initial)
  const inc = () => count.value++
  const dec = () => count.value--
  return { count, inc, dec }
}

<!-- AVOID: returning plain values (loses reactivity) -->
export function badCounter() {
  let count = 0  // plain variable — NOT reactive!
  return { count, inc: () => count++ }
}

<!-- DO: accept refs/getters for flexible inputs -->
export function useSearch(query) {
  // query can be a ref, a getter, or a plain value
  return watchEffect(() => fetch('/api?q=' + unref(query)))
}
17

リアクティビティの深掘り

リアクティブ Proxy のメカニズム

Vue 3 のリアクティビティは、Proxy(ES6)を使います。get(依存を追跡するため)と set(更新をトリガーするため)を傍受する Proxy を返すのが、reactive() です。元のオブジェクトは修正されません — ラップされたバージョンが得られます。何かがリアクティブな Proxy かチェックするのが、isReactive() です。Vue 2 の Object.defineProperty のアプローチ(新しいプロパティの追加を検出できませんでした)より強力です。

vue3
<script setup>
import { reactive, isReactive, isProxy } from 'vue'

const state = reactive({ count: 0 })

// reactive() wraps the object in a Proxy
// reads/writes are tracked and trigger updates
state.count++  // triggers re-render

// the original object is NOT reactive
const raw = { count: 0 }
const wrapped = reactive(raw)
console.log(raw === wrapped)         // false
console.log(isReactive(wrapped))     // true
console.log(isReactive(raw))         // false
console.log(isProxy(wrapped))        // true
</script>

ref のアンラップの規則

ref のアンラップの規則:<script> では .value 経由でアクセスし、テンプレートとリアクティブなオブジェクトの内側では、refs が .value へ自動的にアンラップします。テンプレートの {{ count }} が .value なしで機能する理由が、これです。アンラップは浅いです — 配列/Maps のネストした refs はアンラップしません。refs を含むリアクティブなオブジェクトは、割り当て時に ref の値をミューテートします:state.count = 5 が、count.value = 5 を設定します。

vue3
<script setup>
import { ref, reactive } from 'vue'

const count = ref(0)
const state = reactive({ count })

// in JS: ref needs .value
count.value = 1

// in reactive object: ref auto-unwraps
console.log(state.count)  // 1 (not count.value)
state.count = 5           // updates count.value

// in templates: ref auto-unwraps
// {{ count }} renders count.value
</script>

<template>
  <p>{{ count }}</p>  <!-- 5, not [object Object] -->
</template>

Effect と track/trigger(内部)

リアクティビティの背後の低レベルのプリミティブであるのが、effect() です — 関数を走らせ、内側のすべてのリアクティブな読み取りを追跡し、追跡された値のいずれかが変わると再実行します。computed、watch、watchEffect、コンポーネントのレンダリングが、すべて effect の上に構築されます。アプリのコードで直接 effect() を呼ぶことはめったにありません — computed/watch/watchEffect を優先しましょう — しかし、エンジンがこれです。これを理解すると、並べ替えとタイミングの推論に役立ちます。

vue3
<script setup>
import { ref, effect } from 'vue'

const count = ref(0)

// effect runs immediately, then re-runs on dep change
effect(() => {
  console.log('count is', count.value)
})
// logs: count is 0

count.value = 10
// logs: count is 10

// internally:
// - effect tracks dependencies accessed inside it
// - setting count.value triggers all tracked effects
</script>

markRaw と readonly

オブジェクトを恒久的にリアクティビティから外すのが、markRaw() です — 独自の更新機構を持ち、Proxy で包まれるべきでない、サードパーティのクラスのインスタンス(チャート、マップ、ゲームの状態)に有用です。リアクティブなオブジェクトの読み取り専用のビューを作るのが、readonly() で、ミューテーションの試みは開発モードで警告します。直接のミューテーションを防ぎながら、composables/ストアから状態を公開するのに、readonly を使いましょう。

vue3
<script setup>
import { reactive, markRaw, readonly, isReadonly } from 'vue'

// markRaw: opt a value OUT of reactivity forever
const bigChart = markRaw(new HeavyChartLib())
const state = reactive({ chart: bigChart })
// state.chart mutations won't trigger Vue updates
// (use chart's own API to update it)

// readonly: make a reactive object read-only
const original = reactive({ count: 0 })
const frozen = readonly(original)
frozen.count = 5
// warning: target is readonly (dev mode)

console.log(isReadonly(frozen))  // true
</script>

カスタム Ref(ファクトリ)

依存の追跡とトリガーを明示的に制御させてくれるのが、customRef() です。ファクトリが、track() と trigger() を受け取ります — 依存を登録するには get() で track() を呼び、更新を通知するには set() で trigger() を呼びます。デバウンスされた refs、遅延 refs、ストレージに裏打ちされた refs のようなパターンを可能にします。強力ですが控えめに使いましょう — 通常、watchEffect + 通常の ref のほうが明確です。

vue3
<script setup>
import { customRef } from 'vue'

// debounce a ref's updates
function debouncedRef(value, delay = 200) {
  let timeout
  return customRef((track, trigger) => ({
    get() {
      track()  // tell Vue this value is a dependency
      return value
    },
    set(newValue) {
      clearTimeout(timeout)
      timeout = setTimeout(() => {
        value = newValue
        trigger()  // notify Vue of the change
      }, delay)
    }
  }))
}

const text = debouncedRef('', 300)
// input only triggers re-render 300ms after typing stops
</script>
18

Vue Router

Router のセットアップ

ルーティングをセットアップするのが、createRouter です。HTML5 の history モードを使うのが、createWebHistory です(きれいな URL、index.html へのサーバーのフォールバックが必要です)。コード分割のために、動的な import() でルートのコンポーネントを遅延ロードしましょう — 各ルートが自身のバンドルになります。route.params 経由でアクセスされるのが、動的なセグメント(:id)です。app.use(router) で、プラグインとしてルーターをインストールしましょう。

vue3
<!-- router/index.js -->
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'

const routes = [
  { path: '/', name: 'home', component: Home },
  {
    path: '/about',
    name: 'about',
    // lazy-load for code-splitting
    component: () => import('../views/About.vue')
  },
  { path: '/user/:id', name: 'user', component: () => import('../views/User.vue') }
]

export const router = createRouter({
  history: createWebHistory(),
  routes
})

<!-- main.js -->
import { createApp } from 'vue'
import App from './App.vue'
import { router } from './router'

createApp(App).use(router).mount('#app')

RouterView と RouterLink

マッチしたルートのコンポーネントが表示されるプレースホルダーであるのが、<RouterView> です。<a> タグを表示するが、(フルページのリロードなしの)クライアントサイドナビゲーションのためにクリックを傍受するのが、<RouterLink> です。to の prop が、文字列のパスかオブジェクト({ name, params, query })を受け付けます。現在のリンクをスタイルするための active/exact-active のクラスを加えるのが、RouterLink です。

vue3
<!-- App.vue -->
<template>
  <nav>
    <!-- RouterLink renders <a>, handles navigation -->
    <RouterLink to="/">Home</RouterLink>
    <RouterLink to="/about">About</RouterLink>
    <RouterLink :to="{ name: 'user', params: { id: 42 } }">
      User 42
    </RouterLink>
  </nav>

  <!-- matched route's component renders here -->
  <RouterView />
</template>

ナビゲーションとプログラマティックルーティング

ナビゲーションのためのルーターのインスタンスを与えるのが、useRouter() で、現在のルート(リアクティブ)を与えるのが、useRoute() です。履歴のエントリを加えるのが(戻るボタンが機能します)、push で、しないのが、replace です。リアクティブであるのが(path、params、query、hash、name、matchedの)ルートのプロパティで、ナビゲーションでウォッチャーと computed が再実行します。アプリ内のナビゲーションには、常に router.push を使いましょう — SPA を保つため、window.location を使ってはいけません。

vue3
<script setup>
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

// push to a new URL (adds to history)
function goHome() {
  router.push('/')
  router.push({ name: 'user', params: { id: 1 } })
  router.push({ path: '/search', query: { q: 'vue' } })
}

// replace current entry (no back button)
router.replace('/login')

// go back/forward
router.back()
router.forward()
router.go(-2)

// access current route info
console.log(route.path, route.params.id, route.query.q)
</script>

Route Guards

ナビゲーションのフローを制御するのが、guards です。auth のチェックに最適なのが、グローバルの beforeEach です。特定のルートを守るのが、ルートごとの beforeEnter です。未保存の変更の警告に有用なのが、コンポーネント内の guards(onBeforeRouteLeave、onBeforeRouteUpdate)です。キャンセル/リダイレクトするには、false かルートを返し、確認するには、true/undefined を返しましょう。非同期の guards は、Promise を返せます。requiresAuth のようなフラグを付けるのが、route.meta です。

vue3
<!-- router/index.js -->
const router = createRouter({ history, routes })

// global guard: runs on every navigation
router.beforeEach((to, from) => {
  if (to.meta.requiresAuth && !isAuthenticated()) {
    return '/login'  // redirect
  }
  // return true or undefined to confirm
})

// per-route guard
{ path: '/admin', component: Admin, beforeEnter: (to, from) => {
  if (!isAdmin()) return '/403'
}}

// in-component guard
<script setup>
import { onBeforeRouteLeave } from 'vue-router'
onBeforeRouteLeave((to, from) => {
  if (hasUnsavedChanges()) {
    return confirm('Discard changes?')
  }
})
</script>

遅延ロードとネストしたルート

親の <RouterView> の内側に子のコンポーネントを表示するのが、ネストしたルートです。親に相対的なパスで、children を定義しましょう。親の URL に正確に一致するのが、空のパス('')です。各ルートを自身のバンドルへコード分割するのが、動的な import() です。データ(auth の要件、タイトル)を付けるのが、route.meta で — guards から to.meta 経由でアクセスできます。chunk 名のコメントで、関連するルートをバンドルしましょう。

vue3
const routes = [
  {
    path: '/dashboard',
    component: () => import('../views/Dashboard.vue'),
    children: [
      { path: '', component: () => import('../views/Overview.vue') },
      { path: 'stats', component: () => import('../views/Stats.vue') },
      { path: 'settings', component: () => import('../views/Settings.vue') }
    ]
  },
  // group routes into one chunk
  {
    path: '/admin',
    component: () => import(/* webpackChunkName: "admin" */ '../views/Admin.vue'),
    meta: { requiresAuth: true, role: 'admin' }
  }
]
19

状態管理(Pinia)

ストアの定義

Vue の公式の状態管理であるのが(Vuex の後継)、Pinia です。setup 関数付きの defineStore が、Composition API の構文を与えます — state/getters であるのが ref/computed で、actions であるのが返される関数です。一意のストアの id であるのが、最初の引数です。Setup のストアは柔軟です(内側で任意の composable を使えます)。あるいは、より Vuex 風の感覚のために、Options の構文(state/getters/actions のオブジェクト)を使いましょう。

vue3
<!-- stores/counter.js -->
import { defineStore } from 'pinia'

// setup syntax (composition API style)
export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const double = computed(() => count.value * 2)

  function increment() {
    count.value++
  }

  function asyncIncrement() {
    setTimeout(() => count.value++, 1000)
  }

  return { count, double, increment, asyncIncrement }
})

ストアの使用

ストアへアクセスするには、setup の内側で useStore() を呼びましょう。リアクティブな分解のためには、storeToRefs() を使いましょう(toRefs のようですが、actions をスキップします)。直接分解できるのが(ストアにバインドされるため)、actions です。Pinia は、直接のミューテーション(counter.count = 5)と、バッチ更新のための $patch を許します。シングルトンであるのが、stores です — すべてのコンポーネントをまたいだ同じインスタンスです。app.use(createPinia()) で、Pinia をインストールしましょう。

vue3
<script setup>
import { useCounterStore } from '../stores/counter'
import { storeToRefs } from 'pinia'

const counter = useCounterStore()

// state and getters lose reactivity if destructured directly
// use storeToRefs to preserve it
const { count, double } = storeToRefs(counter)

// actions can be destructured directly (they're functions)
const { increment } = counter

// mutate state directly (Pinia allows it, unlike Vuex)
counter.count = 5
counter.$patch({ count: 10 })
counter.$patch(state => { state.count++ })
</script>

<template>
  <p>{{ count }} x 2 = {{ double }}</p>
  <button @click="increment">+</button>
</template>

Getters とストアの合成

状態から派生する computed の値であるのが、getters です。内側で別のストアを使うには、単にその useStore() を呼びましょう — Pinia が依存を扱います。これにより、(Vuex のモジュールと違い)ストアの合成が自明になります。他の getters を参照できるのが、getters です。非同期の操作のためには、単にストアで async の関数を書きましょう — Vuex のような特別な「actions」のコンテキストはありません。

vue3
<!-- stores/cart.js -->
import { defineStore } from 'pinia'
import { useUserStore } from './user'

export const useCartStore = defineStore('cart', () => {
  const items = ref([])

  // getter (computed)
  const total = computed(() =>
    items.value.reduce((sum, i) => sum + i.price * i.qty, 0)
  )

  const itemCount = computed(() =>
    items.value.reduce((n, i) => n + i.qty, 0)
  )

  // compose other stores
  const userStore = useUserStore()
  const canCheckout = computed(() =>
    userStore.isLoggedIn && items.value.length > 0
  )

  function addItem(item) {
    items.value.push(item)
  }

  return { items, total, itemCount, canCheckout, addItem }
})

購読と永続化

(ミューテーションの情報と新しい状態付きで)任意の状態の変化で発火するのが、$subscribe です。永続化(localStorage、sessionStorage)や外部システムへの同期に使いましょう。アクションの呼び出しにフックするのが、$onAction で — ログ、分析、アクションの期間の計測に有用です。アクションの完了か失敗に反応させてくれるのが、after/onError のコールバックです。コンポーネントのアンマウントで自動的に起こるのが、クリーンアップです。

vue3
<script setup>
import { useCartStore } from '../stores/cart'

const cart = useCartStore()

// subscribe to any state change
cart.$subscribe((mutation, state) => {
  console.log('cart changed', mutation.type, state)
  // persist to localStorage
  localStorage.setItem('cart', JSON.stringify(state.items))
})

// subscribe to actions
cart.$onAction(({ name, after, onError }) => {
  console.log('action started:', name)
  after(result => console.log('action done:', name, result))
  onError(err => console.error('action failed:', name, err))
})
</script>

リセットとストアのモジュール

組み込みの $reset() を持つのが、Options 構文のストアです。setup のストアは持たず、各 ref を再割り当てすることで、reset() を手動で実装しましょう。モジュラーな設計であるのが、Pinia です — 各ストアが独立しており、Vuex のようなネストしたモジュールがありません。内側で useOtherStore() を呼ぶことで、ストアを合成しましょう。createPinia() で、Pinia をグローバルにインストールしましょう。ツリーシェイカブルで、優れた TypeScript の対応と devtools の統合を持つのが、stores です。

vue3
<!-- stores/user.js -->
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', () => {
  const name = ref('')
  const isLoggedIn = ref(false)

  function login(n) { name.value = n; isLoggedIn.value = true }
  function logout() { name.value = ''; isLoggedIn.value = false }

  // Pinia setup stores don't have a built-in $reset
  // implement it manually
  function reset() {
    name.value = ''
    isLoggedIn.value = false
  }

  return { name, isLoggedIn, login, logout, reset }
})

<!-- main.js -->
import { createPinia } from 'pinia'
const pinia = createPinia()
app.use(pinia)
20

トランジションとアニメーション

Transition コンポーネント

enter/leave をアニメーション化するには、v-if/v-show の要素を <Transition> で包みましょう。Vue が適切なタイミングで 6 つのクラスを加えます:*-enter-from(開始状態)、*-enter-active(トランジションの間)、*-enter-to(終了状態)、そして *-leave-* です。これらのクラス上で CSS のトランジション/アニメーションを定義しましょう。「v-」の接頭辞を置き換えるのが、name の prop です。許されるのは単一の子要素だけです。リストには、TransitionGroup を。

vue3
<template>
  <Transition name="fade">
    <p v-if="show">Hello</p>
  </Transition>
</template>

<style>
/* 6 classes: {name}-enter-{from,active,to}, {name}-leave-{...} */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>

Transition のモードとフック

入る要素が始まる前に、離れる要素を完全にアニメーションで外に出すのが、mode='out-in' です — 重なりなしでコンポーネント(タブ)を交換するのに最適です。めったに使われないのが、mode='in-out' です。GSAP のようなライブラリでアニメーションを駆動させてくれるのが、(@before-enter、@enter、@leave の)JavaScript のフックです。CSS の検出をスキップし、JS のフックだけに頼るよう Vue に伝えるのが、:css='false' です(わずかなパフォーマンスの勝利)。

vue3
<template>
  <!-- 'out-in': current leaves, then new enters -->
  <Transition mode="out-in" name="fade">
    <component :is="currentTab" />
  </Transition>

  <!-- JavaScript hooks for GSAP/anime.js -->
  <Transition
    @before-enter="beforeEnter"
    @enter="enter"
    @leave="leave"
    :css="false"
  >
    <div v-if="show">Animated</div>
  </Transition>
</template>

リストのための TransitionGroup

3 つの挙動で、v-for のリストをアニメーション化するのが、TransitionGroup です:enter(新しいアイテム)、leave(取り除かれたアイテム)、move(位置を変える既存のアイテム)です。FLIP の技法をアニメーション化するのが、*-move クラスで — Vue が位置の差分を計算し、transform のトランジションを適用します。離れるアイテムがフローから外れ、兄弟が滑らかに所定の位置へスライドできるよう、leave-active に position: absolute を設定しましょう。

vue3
<template>
  <TransitionGroup name="list" tag="ul">
    <li v-for="item in items" :key="item.id">{{ item.text }}</li>
  </TransitionGroup>
</template>

<style>
.list-enter-active, .list-leave-active { transition: all 0.5s; }
.list-enter-from, .list-leave-to { opacity: 0; transform: translateX(30px); }
/* the magic class for reordering */
.list-leave-active { position: absolute; }
.list-move { transition: transform 0.5s ease; }
</style>

<Transition> ラッパーでのアニメーション化された状態

Vue のデフォルトのクラス名をカスタムのもの(enter-active-class、leave-active-class)で上書きできます。既存のアニメーションシステム(Animate.css、Tailwind のアニメーションのユーティリティ、カスタムキーフレーム)へ差し込めます。パターン:クラス上にアニメーションを定義し、Vue の transition をそれに向けましょう。Vue のライフサイクルを、任意の CSS のアニメーションフレームワークと橋渡しするのが、これです。

vue3
<template>
  <button @click="show = !show">Toggle</button>
  <Transition
    enter-active-class="animate__animated animate__fadeIn"
    leave-active-class="animate__animated animate__fadeOut"
  >
    <div v-if="show" class="box">Content</div>
  </Transition>
</template>

<!-- combine with third-party animation libraries -->
<!-- Animate.css, Tailwind animations, custom keyframes -->

非同期のための Suspense

非同期の setup を調整するのが、Suspense です — 子のコンポーネントがトップレベルの await を使うと、サスペンドし、Suspense が代わりに #fallback を表示します。すべての非同期の子が解決されると、デフォルトのスロットが表示されます。データフェッチのコンポーネントにエレガントです。注意:Suspense は、Vue 3 でまだ実験的です — エラー処理には onErrorCaptured が必要です。本番では、ほとんどのチームがまだ composables + loading の状態を使います。

vue3
<template>
  <Suspense>
    <template #default>
      <AsyncComponent />
    </template>
    <template #fallback>
      <div>Loading...</div>
    </template>
  </Suspense>
</template>

<!-- AsyncComponent uses top-level await -->
<script setup>
import { ref } from 'vue'
const data = ref(null)
// top-level await suspends the component
const res = await fetch('/api/data').then(r => r.json())
data.value = res
</script>
21

Teleport と Suspense

Teleport の基本

文書の別のところ(多くの場合 body レベル)の DOM 要素へコンテンツを表示するのが、Teleport です。しかし、コンポーネントは、親のリアクティブなコンテキスト、props、emits などを保ちます。親の overflow:hidden やスタッキングコンテキストにクリップされる、モーダル、ツールチップ、ドロップダウンの z-index/overflow の問題を解決するのが、これです。目的地の要素を狙うのが、「to」のセレクタです。

vue3
<!-- Modal.vue -->
<template>
  <!-- the rendered content is moved to #modals in the DOM,
       but keeps the component's reactive context -->
  <Teleport to="#modals">
    <div class="modal">
      <h2>{{ title }}</h2>
      <slot />
      <button @click="$emit('close')">Close</button>
    </div>
  </Teleport>
</template>

<!-- index.html must have -->
<!-- <div id="app"></div> -->
<!-- <div id="modals"></div> -->

条件付きの Teleport

条件付きで teleport させてくれるのが、disabled の prop です — true のとき、(teleport されず)コンテンツがその場で表示されます。同じコンポーネントが異なるコンテキストで使われるとき有用です(例:通常のレイアウトでは teleport されるべきだが、別のモーダルの内側ではインラインのツールチップです)。同じ要素を狙う複数の Teleport が、レンダリング順で append します。Teleport は、内側の v-if と機能します。

vue3
<template>
  <!-- disabled: render in place (not teleported) -->
  <Teleport :to="target" :disabled="inline">
    <div class="popup" v-if="show">...</div>
  </Teleport>
</template>

<script setup>
const props = defineProps({
  inline: Boolean  // if true, render inline instead of teleporting
})
const target = '#popups'
</script>

<!-- Multiple Teleports to same target: appended in order -->

モーダルと通知のための Teleport

モーダルの標準のパターンであるのが、body への Teleport です — モーダルが、任意の親の overflow/transform/z-index の制約から逃れます。enter/leave のアニメーションのために、Transition と組み合わせましょう。コンテンツの外のクリックで(コンテンツ上ではなく)閉じるのが、バックドロップの @click.self です。親が、モーダルの header、body、footer を完全にカスタマイズでき、位置とアニメーションをモーダルのコンポーネントが扱うのが、slots です。

vue3
<!-- components/Modal.vue -->
<template>
  <Teleport to="body">
    <Transition name="modal">
      <div v-if="show" class="modal-backdrop" @click.self="$emit('close')">
        <div class="modal-content">
          <header><slot name="header" /></header>
          <slot />
          <footer><slot name="footer" /></footer>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

非同期の Setup での Suspense

子のコンポーネントの setup がトップレベルの await を使うと、Promise を返します。Suspense がそれを捉え、解決まで #fallback を表示します。サスペンドされたコンポーネントの setup の結果が、その後、レンダリングに使われます。複数の非同期の子が調整されます — Suspense がすべてを待ちます。setup のエラーを捉えるのが、onErrorCaptured です。Suspense はまだ実験的です — 本番のためには、composables での手動の loading の状態を優先しましょう。

vue3
<!-- Parent.vue -->
<template>
  <Suspense>
    <AsyncProfile :id="userId" />
    <template #fallback>
      <Spinner />
    </template>
  </Suspense>
</template>

<!-- AsyncProfile.vue -->
<script setup>
const props = defineProps(['id'])
// top-level await suspends this component
const profile = await fetch(`/api/users/${props.id}`).then(r => r.json())
// component only renders after this resolves
</script>

ネストした Suspense と非同期のコンポーネント

ネストできるのが、Suspense です — 各レベルが自身の非同期の境界を扱います。Dashboard(とその必要なすべて)がロードされる間、外の Suspense が PageSkeleton を表示し、内のものが、チャート専用に ChartSkeleton を表示します。この粒度の細かいローディングが UX を改善します:ページのシェルが最初に現れ、その後、個々のセクションが満たされます。Suspense は実験的であることを覚えておきましょう — 徹底的にテストし、onErrorCaptured でエラーを扱いましょう。

vue3
<template>
  <Suspense>
    <template #default>
      <Dashboard>
        <Suspense>
          <template #default>
            <AsyncChart :data="data" />
          </template>
          <template #fallback>
            <ChartSkeleton />
          </template>
        </Suspense>
      </Dashboard>
    </template>
    <template #fallback>
      <PageSkeleton />
    </template>
  </Suspense>
</template>
22

Provide / Inject

基本の Provide と Inject

値をすべての子孫のコンポーネントへ利用可能にするのが、provide() で、ツリーの下のどこでもそれを取り出すのが、inject() です。深くネストしたコンポーネントのための、prop-drilling を避けられます。inject の第 2 引数が、(何も提供されないとき使われる)デフォルト値です。提供された refs はリアクティブです — 子孫がそれらをミューテートでき、親が変更を見ます。大きなアプリでの衝突を避けるには、Symbol のキーを使いましょう。

vue3
<!-- Parent.vue -->
<script setup>
import { provide, ref } from 'vue'

const theme = ref('dark')
const user = ref({ name: 'Alice' })

// provide to all descendants
provide('theme', theme)
provide('user', user)
</script>

<!-- DeepChild.vue (any level of nesting) -->
<script setup>
import { inject } from 'vue'

const theme = inject('theme', 'light')  // default 'light'
const user = inject('user')

// these are reactive refs, just like in the parent
</script>

読み取り専用の提供された状態

直接のミューテーションを許さずに状態を公開するのが、readonly() です — 変更するには、子孫が提供されたアクションのメソッドを呼ばなければなりません。このパターン(プライベートの可変 ref + readonly の公開ビュー + アクションのメソッド)が、コンポーネントツリーのスコープの状態のための、Pinia の軽量な代替です。一方向のデータフローを強制し、ツリーの深いところでのランダムなミューテーションからのバグを防ぎます。

vue3
<!-- store.js (shared composable) -->
import { ref, readonly } from 'vue'

const _count = ref(0)  // private mutable state

export function useCountStore() {
  return {
    count: readonly(_count),  // consumers can't mutate
    increment: () => _count.value++  // only via action
  }
}

<!-- Provider.vue -->
<script setup>
import { provide } from 'vue'
import { useCountStore } from './store'

const store = useCountStore()
provide('countStore', store)
</script>

型付きの Injection のキー

型付きのシンボルのキーを作るのが、InjectionKey<Ref<Type>> です。完全な TypeScript の推論が得られます — inject が戻り値の型を知ります。複数のライブラリが値を提供するとき、文字列の衝突を避けるのが、Symbol のキーです。アプリ全体のシングルトンのためには、provide/inject より Pinia を優先しましょう — Pinia には、devtools、永続化、より良いテスト可能性があります。コンポーネントツリーのスコープのコンテキスト(テーマ、フォーム、ロケール)には、provide/inject を使いましょう。

vue3
<!-- keys.ts -->
import type { InjectionKey, Ref } from 'vue'
import { inject, provide } from 'vue'

export const ThemeKey: InjectionKey<Ref<string>> = Symbol('theme')

<!-- Provider.vue -->
<script setup>
import { ref } from 'vue'
import { ThemeKey } from './keys'

const theme = ref('dark')
provide(ThemeKey, theme)
</script>

<!-- Consumer.vue -->
<script setup>
import { inject } from 'vue'
import { ThemeKey } from './keys'

// TS knows theme is Ref<string> | undefined
const theme = inject(ThemeKey)
// with default
const theme2 = inject(ThemeKey, ref('light'))
</script>

提供された値の更新

推奨されるパターン:リアクティブな状態と、それをミューテートするメソッドを含むオブジェクトを提供しましょう。API が明確に保たれ、ランダムなミューテーションが防がれます。子が、状態とアクションを分解します。これは本質的にミニストアです — いくつかの値を超えるもののためには、同じ shape を返す composable か、Pinia を考えましょう。ref を含むため、提供された値がリアクティブです。

vue3
<!-- Provider.vue -->
<script setup>
import { ref, provide } from 'vue'

const count = ref(0)

// expose value + mutator together
provide('counter', {
  count,                       // reactive ref
  increment: () => count.value++,
  reset: () => count.value = 0
})
</script>

<!-- DeepChild.vue -->
<script setup>
import { inject } from 'vue'

const { count, increment, reset } = inject('counter')
// count is reactive, increment/reset are actions
</script>

<template>
  <p>{{ count }}</p>
  <button @click="increment">+</button>
  <button @click="reset">Reset</button>
</template>

アプリレベルの Provide

アプリのすべてのコンポーネントへ値を利用可能にするのが、app.provide() です — アプリ全体の定数(API の URL、機能フラグ、環境の設定)に有用です。コンポーネントレベルの provide と違い、(ref を提供しない限り)デフォルトでリアクティブではありません。env ファイルをあちこちでインポートせずに、環境固有の設定を注入する良い方法です。これらのグローバルへアクセスするには、任意のコンポーネントの inject() と組み合わせましょう。

vue3
<!-- main.js -->
import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

// app-level provide — available to ALL components
app.provide('apiUrl', 'https://api.example.com')
app.provide('apiKey', import.meta.env.VITE_API_KEY)

// useful for app-wide constants
app.provide('features', {
  darkMode: true,
  beta: false
})

app.mount('#app')

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.