Vue3 の高度な機能と内部構造

カスタムディレクティブと高度な機能

ディレクティブの実装

コンポーネント内でのローカルディレクティブ定義:

<template>
  <input type="text" v-select>
</template>

<script>
export default {
  directives: {
    select: {
      mounted(element) {
        element.select();
      }
    }
  }
}
</script>

グローバルディレクティブ登録:

import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);
app.directive("highlight", {
  mounted(el) {
    el.style.backgroundColor = 'yellow';
  }
});
app.mount('#app');

ディレクティブのライフサイクル

Vue3 説明
created属性バインディング前
beforeMount初回要素バインディング時
mounted親コンポーネントマウント後
beforeUpdateコンポーネント更新前
updatedコンポーネント更新後
beforeUnmount親コンポーネントアンマウント前
unmounted要素バインディング解除後

ディレクティブの修飾子と引数

<template>
  <button v-user.role="'admin'">管理者</button>
</template>

<script>
export default {
  directives: {
    user: {
      created(el, binding) {
        console.log('引数:', binding.value);
        console.log('修飾子:', binding.modifiers);
      }
    }
  }
}
</script>

Teleport の活用

<template>
  <div class="container"></div>
  <teleport to=".external-container">
    <div>外部要素</div>
  </teleport>
</template>

プラグインの開発

オブジェクト形式プラグイン:

export default {
  install(app) {
    app.config.globalProperties.$version = '3.0.0';
  }
}

関数形式プラグイン:

export default function(app) {
  app.config.globalProperties.$environment = 'production';
}

Vue3 内部構造の解析

仮想DOMの利点

  • DOM操作の抽象化による開発効率向上
  • 直接的なDOM操作の削減によるパフォーマンス改善
  • クロスプラットフォーム対応の実現

仮想DOMの処理フロー

テンプレート → レンダー関数 → VNode → 差分検出 → DOM更新

コアシステム

  • コンパイラ:テンプレート変換
  • レンダラ:実際の描画処理
  • リアクティブ:データバインディング

Vue Router の実装

ルーティング基本設定

import { createRouter, createWebHistory } from 'vue-router';

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
];

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

動的ルートパラメータ

const routes = [
  { path: '/user/:id', component: UserProfile }
];

Vuex 状態管理

ストアの基本構造

import { createStore } from 'vuex';

export default createStore({
  state: {
    count: 0
  },
  mutations: {
    increment(state, payload) {
      state.count += payload.value;
    }
  },
  actions: {
    asyncIncrement({ commit }) {
      commit('increment', { value: 5 });
    }
  }
});

モジュール化

const userModule = {
  namespaced: true,
  state: { username: '' },
  mutations: {
    setUsername(state, name) {
      state.username = name;
    }
  }
};

補足技術

nextTick の利用

<script>
import { ref, nextTick } from 'vue';

export default {
  setup() {
    const message = ref('');
    
    const updateContent = async () => {
      message.value = '更新内容';
      await nextTick();
      console.log('DOM更新完了');
    };

    return { updateContent };
  }
}
</script>

History API フォールバック

// vue.config.js
module.exports = {
  devServer: {
    historyApiFallback: true
  }
};

タグ: Vue3 カスタムディレクティブ Vueプラグイン 仮想DOM VueRouter

6月16日 16:48 投稿