8.

【Vue.js】ライフサイクルフック(created / mounted / updated / destroyedの使い方)

編集
この記事の要点
  • Vue.js のライフサイクルフックは、コンポーネントの生成〜破棄までの各タイミングで実行される関数
  • Vue 2: beforeCreate / created / beforeMount / mounted / beforeUpdate / updated / beforeDestroy / destroyed
  • Vue 3: setup + onBeforeMount / onMounted / onBeforeUpdate / onUpdated / onBeforeUnmount / onUnmounted
  • created は DOM 生成前、mounted は DOM 利用可能後
  • API 呼び出しは created or mounted、DOM 操作は mounted

 

Vue.js のライフサイクル全体図

フェーズVue 2 フックVue 3 フック (Composition API)タイミング
1. 生成前beforeCreatesetup()data / props / methods 未準備
2. 生成後createdsetup()data / props 利用可、DOM はまだない
3. マウント前beforeMountonBeforeMountテンプレートのコンパイル直後、DOM 挿入前
4. マウント後mountedonMountedDOM が利用可能
5. 更新前beforeUpdateonBeforeUpdatedata 変更後、再描画前
6. 更新後updatedonUpdated再描画後
7. 破棄前beforeDestroy (Vue 2) / beforeUnmount (Vue 3)onBeforeUnmountコンポーネント破棄直前
8. 破棄後destroyed (Vue 2) / unmounted (Vue 3)onUnmountedコンポーネント破棄後

Vue 2 の Options API 例

export default {
    data() {
        return { message: "Hello" };
    },

    beforeCreate() {
        console.log("beforeCreate: data はまだ未定義", this.message);  // undefined
    },

    created() {
        console.log("created: data 利用可", this.message);  // "Hello"
        // API 呼び出しによく使われる
        this.fetchData();
    },

    beforeMount() {
        console.log("beforeMount: DOM 挿入直前");
    },

    mounted() {
        console.log("mounted: DOM 利用可");
        // jQuery プラグイン初期化や、子要素のサイズ取得
        const elem = this.$refs.myDiv;
        const rect = elem.getBoundingClientRect();

        // DOM イベントリスナー
        window.addEventListener("resize", this.handleResize);
    },

    beforeUpdate() {
        console.log("beforeUpdate: data 変更直後、DOM 反映前");
    },

    updated() {
        console.log("updated: DOM 反映済み");
    },

    beforeDestroy() {  // Vue 3 では beforeUnmount
        console.log("beforeDestroy: 後片付け");
        window.removeEventListener("resize", this.handleResize);
    },

    destroyed() {  // Vue 3 では unmounted
        console.log("destroyed");
    },

    methods: {
        async fetchData() {
            const res = await fetch("/api/data");
            this.message = await res.json();
        },
        handleResize() { /* ... */ }
    }
};

Vue 3 の Composition API 例

主要フックの使い分け

created(Vue 2) / setup(Vue 3)

  • data / props にアクセス可
  • API 呼び出し(初期データ取得)
  • DOM はまだないので $refs はアクセス不可

mounted / onMounted

  • DOM が完成、$refs アクセス可
  • サードパーティライブラリの初期化(jQuery プラグイン、Chart.js 等)
  • 子要素のサイズ計算
  • DOM イベントリスナー追加

updated / onUpdated

  • data 変更 → DOM 再描画後に呼ばれる
  • 注意: ここで data を変更すると無限ループ
  • 使用例: チャートの再描画、スクロール位置調整

beforeUnmount / onBeforeUnmount

  • イベントリスナー削除
  • setInterval / setTimeout のクリア
  • WebSocket クローズ

API 呼び出しは created か mounted か?

初期データの取得はどちらでも動くが、推奨は:

  • created を推奨: DOM 描画前に開始できる、ローディングが速く感じる
  • mounted が必要なケース: API レスポンスを DOM 要素のサイズ計算等に使う場合
// 推奨パターン (created)
created() {
    this.loading = true;
    this.fetchData().finally(() => this.loading = false);
}

// Vue 3
async function setup() {
    const loading = ref(true);
    try {
        await fetchData();
    } finally {
        loading.value = false;
    }
    return { loading };
}

Vue 2 → Vue 3 移行マッピング

Vue 2Vue 3 (Options API)Vue 3 (Composition API)
beforeCreatebeforeCreatesetup の最初
createdcreatedsetup の中
beforeMountbeforeMountonBeforeMount
mountedmountedonMounted
beforeUpdatebeforeUpdateonBeforeUpdate
updatedupdatedonUpdated
beforeDestroybeforeUnmountonBeforeUnmount
destroyedunmountedonUnmounted
activated (keep-alive)activatedonActivated
deactivateddeactivatedonDeactivated
errorCapturederrorCapturedonErrorCaptured

nextTick との組み合わせ

DOM 反映完了直後に処理を入れたい場合は nextTick:

// Vue 2
mounted() {
    this.message = "Updated";
    this.$nextTick(() => {
        console.log("DOM 反映完了");
        // 高さ計算等
    });
}

// Vue 3
import { nextTick } from "vue";
onMounted(async () => {
    message.value = "Updated";
    await nextTick();
    console.log("DOM 反映完了");
});

関連記事

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. インストール(ファイルのダウンロード)
  2. npmを使用したプロジェクトの作成(mac)
  3. for 繰り返し処理
  4. ifの条件分岐とtemplateを用いたグループ化
  5. on:click クリック時のイベント処理
  6. modelとdata フォーム入力値とDOMへの即時反映
  7. computed(算出プロパティ)と使い方とdataとの違い
  8. ライフサイクルフック(created / mounted / updated / destroyedの使い方)
  9. $nextTickの使い方(ライフサイクルフック)
  10. メソッドの定義方法
  11. エラー一覧
  12. ルーティング設定
  13. aリンクの貼り方と動的URLの作成
  14. Mixinを利用した共通処理の記述方法
  15. v-bindによるデータ連携
  16. ヘッダー/フッターの共通コンポーネント
  17. ナビゲーションの現在ページをハイライトする方法
  18. 画面サイズの取得方法