0 day streak
javascript / intermediate
Snippet

Managing Component Flow with an Object-Oriented State Machine

An object-oriented finite state machine class encapsulates state transition maps and validation logic. Storing this state machine inside a Vue ref provides predictable, declarative control flow for complex multi-step forms or wizard components.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { ref } from 'vue';
class CheckoutStateMachine {
#transitions = {
cart: ['shipping'],
shipping: ['payment', 'cart'],
payment: ['confirmation', 'shipping'],
confirmation: []
};
constructor(initialState = 'cart') {
this.currentState = initialState;
}
canTransitionTo(nextState) {
return this.#transitions[this.currentState]?.includes(nextState) ?? false;
}
transition(nextState) {
if (!this.canTransitionTo(nextState)) {
return false;
}
this.currentState = nextState;
return true;
}
}
export function useCheckoutFlow() {
const fsm = ref(new CheckoutStateMachine('cart'));
return { fsm };
}
vue
Breakdown
1
class CheckoutStateMachine {
Defines a class to govern valid application lifecycle transitions.
2
#transitions = {
Stores state graph mapping as a private property to protect transition integrity.
3
canTransitionTo(nextState) {
Checks if moving to the requested state conforms to defined transition rules.
4
transition(nextState) {
Applies the state transition conditionally and returns a boolean status.