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로 변환
- 글로벌 범위: 모듈 수준에서 상태를 관리하여 모든 구성 요소에서 액세스 가능
사용법
<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