Developing a Plugin Idea
I'm focusing on crafting a Vue.js plugin to streamline state management across various modules, per the request. I'm prioritizing compatibility and user-friendliness as core principles.
Designing the Architecture
I've been solidifying the architecture. I'm leaning heavily on Vue 3's reactive system for the central state object, structuring it like State = { moduleA: { ... }, moduleB: { ... } }. Access will likely be via get for retrieval and possibly a dispatch function for actions, or perhaps we keep it very simple with direct modification. I'm currently drafting the API, considering createStore({ modules: { ... } }) and a useStore() hook. I'm focusing on keeping it lightweight.
Evaluating Simplification Options
I'm now revisiting the "Pinia-lite" approach, which feels the most elegant. After trying a Vuex-lite approach with mutations, it felt too verbose. The current thinking is to provide a "SimpleStore" plugin that sits between a reactive global object and something as complex as Pinia. I'm focusing on allowing the definition of modules with state and actions. The plugin will have an install method for integration.
Outlining Action Binding
I'm presently focusing on how to bind the actions to module state internally. My current strategy involves using a proxy or a similar mechanism, ensuring that this within an action function naturally references the appropriate module's state. I'm keen on making the syntax as user-friendly as possible, thinking of how to make it feel natural and intuitive for action invocations. I'm also considering the best way to handle asynchronous operations within actions, ensuring a clean and manageable approach.
Refining the DX
I'm now zeroing in on the developer experience. The useStore(moduleName) composable is critical. Initially, spreading the state felt intuitive, but I realized it breaks reactivity. I'm now implementing the toRefs approach, ensuring updates are reactive. The composable will return the reactive state object alongside the bound actions. The overall architecture is coming together neatly, and I'm nearing a stage where I'll finalize the implementation.
Defining Module Access
I'm now focusing on module access. I'm exploring a useModule composable for type-safe interaction. I'm prioritizing simplifying the architecture while enabling direct access to state properties. After some contemplation, it seems like the best approach is to abstract the lookup logic to avoid accidental overwrites of the module's state. I'm comparing this implementation to Pinia and evaluating how it stacks up as a simplified option.
Here is a lightweight, modular Vue 3 plugin designed to simplify state management. It sits somewhere between using a simple ref and a full library like Pinia.
I call this plugin "SnapState". It focuses on namespaced modules, automatic action binding, and a simple composable API.
1. The Plugin Implementation
Create a file named snap-state.js.
// snap-state.js
import { reactive, inject, readonly } from 'vue';
const STORE_KEY = Symbol('SnapState');
export const createStore = (modules) => {
// 1. Initialize the root reactive state object
const rootState = reactive({});
const boundActions = {};
// 2. Process each module
for (const [namespace, module] of Object.entries(modules)) {
// Initialize module state
// We execute state() if it's a function, or use it directly if object
rootState[namespace] = typeof module.state === 'function'
? module.state()
: module.state;
boundActions[namespace] = {};
// 3. Bind actions to the module's specific state
if (module.actions) {
for (const [actionName, actionFn] of Object.entries(module.actions)) {
// We bind 'this' to the specific module's state node
// This allows `this.count++` inside actions
boundActions[namespace][actionName] = actionFn.bind(rootState[namespace]);
}
}
}
// 4. The Plugin structure
const store = {
rootState,
actions: boundActions,
install(app) {
// Provide the store to the app context
app.provide(STORE_KEY, store);
}
};
return store;
};
// Composables for easy access
export const useStore = () => {
const store = inject(STORE_KEY);
if (!store) {
throw new Error('SnapState has not been installed in this app.');
}
return store;
};
/**
* specific module accessor
* returns { state, actions }
*/
export const useModule = (namespace) => {
const store = useStore();
if (!store.rootState[namespace]) {
throw new Error(`Module "${namespace}" not found.`);
}
return {
state: store.rootState[namespace], // Reactive
actions: store.actions[namespace] // Bound functions
};
};
2. How to Define Modules
Create your modules as simple objects containing state and actions.
modules/user.js
export default {
state: () => ({
name: 'Guest',
isLoggedIn: false
}),
actions: {
login(username) {
// 'this' refers to the local state defined above
this.name = username;
this.isLoggedIn = true;
},
logout() {
this.name = 'Guest';
this.isLoggedIn = false;
}
}
};
modules/counter.js
export default {
state: () => ({
count: 0,
history: []
}),
actions: {
increment() {
this.count++;
this.history.push(`Incremented to ${this.count}`);
},
reset() {
this.count = 0;
this.history = [];
}
}
};
3. Installation
Register the plugin in your main.js entry file.
import { createApp } from 'vue';
import App from './App.vue';
import { createStore } from './snap-state';
// Import your modules
import user from './modules/user';
import counter from './modules/counter';
const app = createApp(App);
// Create and use the store
const store = createStore({
user,
counter
});
app.use(store);
app.mount('#app');
4. Usage in Components
You can now access specific modules easily within your Vue components.
Option A: Accessing a specific module (Recommended)
<script setup>
import { useModule } from './snap-state';
// Get state and actions for the 'user' module
const { state: user, actions: userActions } = useModule('user');
// Get state and actions for the 'counter' module
const { state: counter, actions: counterActions } = useModule('counter');
</script>
<template>
<div class="dashboard">
<h1>Hello, {{ user.name }}</h1>
<button v-if="!user.isLoggedIn" @click="userActions.login('Alice')">
Log In
</button>
<button v-else @click="userActions.logout()">
Log Out
</button>
<div class="counter-area">
<p>Count: {{ counter.count }}</p>
<button @click="counterActions.increment()">+1</button>
</div>
</div>
</template>
Option B: Accessing the Global Store
Useful if you need to read state from Module A while inside a component primarily concerned with Module B.
<script setup>
import { useStore } from './snap-state';
const store = useStore();
const logAllState = () => {
console.log(store.rootState.user.name);
console.log(store.rootState.counter.count);
};
</script>
Why this simplifies things:
- Automatic Namespace binding: You don't need to pass
state arguments into your actions (like Vuex). The plugin automatically binds this inside actions to the corresponding state module.
- Zero Boilerplate: No types (unless desired), no mutations vs actions distinction, no complex configuration.
- Vue Native: It relies entirely on Vue 3's
reactive system, making it incredibly performant and lightweight (less than 1KB).
- Destructuring Friendly: Because
state is returned as a reactive object, you can access properties directly in your template (e.g., user.name) without losing reactivity.