0
0
Vueframework~30 mins

State machines with composables in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
State machines with composables
📖 Scenario: You are building a simple traffic light controller using Vue 3. The traffic light changes colors in a fixed order: green, then yellow, then red, and back to green. You want to manage these states clearly and predictably using a state machine pattern with Vue composables.
🎯 Goal: Create a Vue 3 composable that manages the traffic light states as a state machine. Then use this composable in a component to display the current light color and a button to move to the next state.
📋 What You'll Learn
Create a composable function called useTrafficLight that manages the traffic light states.
Define the states: green, yellow, and red.
Add a function next inside the composable to move to the next state in order.
Create a Vue component that uses useTrafficLight to show the current state and a button to trigger next.
💡 Why This Matters
🌍 Real World
State machines are used in real-world apps to manage complex states clearly, such as UI workflows, game states, or device controls.
💼 Career
Understanding state machines and composables is valuable for frontend developers working with Vue to build maintainable and predictable user interfaces.
Progress0 / 4 steps
1
Set up the traffic light states
Create a composable function called useTrafficLight that returns a reactive variable state initialized to the string 'green'.
Vue
Hint

Use ref from Vue to create a reactive state variable inside the composable.

2
Add the state order configuration
Inside useTrafficLight, create a constant array called states with the values 'green', 'yellow', and 'red' in that order.
Vue
Hint

Use a simple array to list the states in the order they should cycle.

3
Implement the next state function
Inside useTrafficLight, add a function called next that updates state.value to the next state in the states array, cycling back to 'green' after 'red'. Return next from the composable.
Vue
Hint

Find the current state's index, add one, and use modulo to cycle back to zero.

4
Create the Vue component using the composable
Create a Vue component with <script setup> that imports useTrafficLight, calls it to get state and next, and in the template shows the current state and a button labeled Next that calls next on click.
Vue
Hint

Use @click on the button to call next. Display state inside the template.