Global state management can be achieved without using Pinia.
I will summarize a lightweight implementation method using Vue’s reactive and toRefs.
implementation
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 }}Points
- reactive: Create reactive state at module scope
- toRefs: Convert state properties to separate refs
- Global scope: By managing state at the module level, it can be accessed from any component.
How to use
<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>summary
A simple global state can be fully realized using Vue’s standard API without introducing Pinia.
This method is lightweight and easy to understand for small projects or when you need very specific global state.
hsb.horse