logo hsb.horse
← Back to blog index

Blog

Vue Composable to manage global state without Pinia

A lightweight implementation method to achieve global state management using Vue's reactive and toRefs without using Pinia.

Published:

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

  1. reactive: Create reactive state at module scope
  2. toRefs: Convert state properties to separate refs
  3. 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.