ルーティングと状態管理

Vue Routerの基本設定

Vue Routerを使って、SPA内でのページ遷移を設定します。

インストールと設定

まずは、Vue Routerをプロジェクトにインストールします。

npm install vue-router@4

次に、ルーターの設定を行います。

// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';

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

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

export default router;

ナビゲーションガード

ナビゲーションガードを使って、ルートへのアクセスを制御します。

router.beforeEach((to, from, next) => {
  // アクセス制御のロジックをここに記述
  if (to.path === '/secret' && !isUserAuthenticated()) {
    next('/login');
  } else {
    next();
  }
});

Vuexの基本設定

Vuexを使って、アプリケーション全体で状態を管理します。

インストールとストアの設定

Vuexをプロジェクトにインストールします。

npm install vuex@4

ストアを設定します。

// store/index.js
import { createStore } from 'vuex';

const store = createStore({
  state() {
    return {
      count: 0
    };
  },
  getters: {
    doubleCount(state) {
      return state.count * 2;
    }
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  },
  actions: {
    increment({ commit }) {
      commit('increment');
    }
  }
});

export default store;

ステート、ゲッター、ミューテーション、アクションの利用

コンポーネント内でストアの状態を利用します。

<template>
  <div>
    <p>{{ count }}</p>
    <p>{{ doubleCount }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script setup>
import { computed } from 'vue';
import { useStore } from 'vuex';

const store = useStore();

const count = computed(() => store.state.count);
const doubleCount = computed(() => store.getters.doubleCount);

function increment() {
  store.dispatch('increment');
}
</script>