Piniaを使わなくてもグローバルステート管理は実現できる。
VueのreactiveとtoRefsを使った軽量な実装方法をまとめる。
実装
import { reactive, toRefs } from 'vue';
interface State { mode: "dark" | "light" | "system"}
const state = reactive({ mode: "system";})
export function useDataStore() { const { mode } = toRefs(state);
const changeMode = (nextMode: State["mode"]) => { state.mode = nextMode; }
return { mode, changeMode }}ポイント
- reactive: モジュールスコープで reactive な state を作成
- toRefs: state のプロパティを個別の ref に変換
- グローバルスコープ: モジュールレベルで state を管理することで、どのコンポーネントからでもアクセス可能
使い方
<script setup>import { useDataStore } from './store';
const { mode, changeMode } = useDataStore();</script>
<template> <div> <p>Current mode: {{ mode }}</p> <button @click="changeMode('dark')">Dark</button> <button @click="changeMode('light')">Light</button> </div></template>まとめ
シンプルなグローバルステートなら、Piniaを導入せずともVueの標準APIで十分実現できる。
小規模なプロジェクトや、ごく限定的なグローバルステートが必要なときは、この方法が軽量でわかりやすい。
hsb.horse