State machines help manage different states clearly. Using composables in Vue makes state machines reusable and easy to organize.
0
0
State machines with composables in Vue
Introduction
You want to control a button that can be loading, success, or error.
Managing form steps where each step is a different state.
Handling modal dialogs that open, close, or show errors.
Controlling a toggle switch with on and off states.
Syntax
Vue
import { ref } from 'vue'; export function useStateMachine() { const state = ref('initial'); function transition(event) { switch (state.value) { case 'initial': if (event === 'start') state.value = 'running'; break; case 'running': if (event === 'stop') state.value = 'stopped'; break; case 'stopped': if (event === 'reset') state.value = 'initial'; break; } } return { state, transition }; }
Use ref to keep track of the current state reactively.
The transition function changes states based on events.
Examples
Simple state machine with two states: 'idle' and 'active'.
Vue
import { ref } from 'vue'; const state = ref('idle'); function transition(event) { if (state.value === 'idle' && event === 'start') { state.value = 'active'; } }
A toggle machine switching between 'on' and 'off' states.
Vue
import { ref } from 'vue'; function useToggleMachine() { const state = ref('off'); function toggle() { state.value = state.value === 'off' ? 'on' : 'off'; } return { state, toggle }; }
Sample Program
This Vue component shows the current state and buttons to change it. Clicking buttons triggers state changes using the state machine logic.
Vue
<template>
<div>
<p>Current state: {{ state }}</p>
<button @click="transition('start')">Start</button>
<button @click="transition('stop')">Stop</button>
<button @click="transition('reset')">Reset</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
const state = ref('initial');
function transition(event) {
switch (state.value) {
case 'initial':
if (event === 'start') state.value = 'running';
break;
case 'running':
if (event === 'stop') state.value = 'stopped';
break;
case 'stopped':
if (event === 'reset') state.value = 'initial';
break;
}
}
</script>OutputSuccess
Important Notes
State machines make your app predictable by clearly defining allowed state changes.
Composable functions keep state logic reusable and clean.
Use descriptive state names to make your code easy to understand.
Summary
State machines control app states clearly and predictably.
Vue composables help organize state machine logic for reuse.
Use ref and functions to manage and change states.