Vue.jsの基本構造
Vue.jsはデータ駆動型のMVVMフレームワークです:
- Model: バックエンドから提供されるデータ
- View: UIレイヤー
- ViewModel: データバインディング層
データフロー
Model → ViewModel → View
// データ変更時の処理フロー
dataChange() {
this.apiData = response;
this.processData();
this.updateView();
}
ディレクティブ
表示制御
<div v-show="isVisible">可視要素</div>
<section v-if="shouldRender">条件付きレンダリング</section>
リストレンダリング
<ul>
<li v-for="(entry, idx) in itemList" :key="entry.id">
{{ idx }}: {{ entry.name }}
</li>
</ul>
データバインディング
<img :src="imagePath" :alt="imageDescription">
<input v-model="userInput">
ライフサイクルフック
| フェーズ | フック |
|---|---|
| 作成 | beforeCreate, created |
| マウント | beforeMount, mounted |
| 更新 | beforeUpdate, updated |
| 破棄 | beforeDestroy, destroyed |
算出プロパティと監視
computed: {
formattedPrice() {
return `¥${this.price.toLocaleString()}`;
}
},
watch: {
quantity(newVal, oldVal) {
this.stockAlert(newVal > oldVal);
}
}
コンポーネント通信
親子間通信
// 親コンポーネント
<ChildComponent :item-data="parentData" @update-data="handleUpdate">
// 子コンポーネント
props: {
itemData: { type: Object, required: true }
},
methods: {
emitUpdate() {
this.$emit('update-data', newData);
}
}
Vue Router
ルート設定
const routeConfig = [
{ path: '/user/:id', component: UserProfile, props: true }
];
const vueRouter = new VueRouter({
routes: routeConfig
});
ナビゲーションガード
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
状態管理(Vuex)
const store = new Vuex.Store({
state: { counter: 0 },
mutations: {
increment(state, payload) {
state.counter += payload.value;
}
},
actions: {
asyncIncrement({ commit }, payload) {
setTimeout(() => {
commit('increment', payload);
}, 500);
}
}
});
高度な機能
スロット
<template>
<div class="container">
<slot name="header">デフォルトヘッダー</slot>
<slot>デフォルトコンテンツ</slot>
</div>
</template>
動的トランジション
<transition :name="transitionType">
<router-view></router-view>
</transition>
カスタムディレクティブ
Vue.directive('focus', {
inserted: function(el) {
el.focus();
}
});