0
0
Vueframework~30 mins

Actions for modifying state in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Actions for Modifying State in Vue 3
📖 Scenario: You are building a simple Vue 3 app to manage a counter. The counter starts at zero and can be increased or decreased by the user. You will use Vue's Composition API and actions to modify the state.
🎯 Goal: Create a Vue 3 component that shows a counter number and two buttons: one to increase and one to decrease the counter. Use actions (functions) to modify the counter state.
📋 What You'll Learn
Use Vue 3 Composition API with <script setup>
Create a reactive state variable called count starting at 0
Create two action functions called increment and decrement to modify count
Bind the buttons to call the correct action functions
Display the current count value in the template
💡 Why This Matters
🌍 Real World
Managing state with actions is common in interactive web apps like counters, forms, and games.
💼 Career
Understanding how to modify state with actions in Vue is essential for frontend developer roles working with modern frameworks.
Progress0 / 4 steps
1
Set up the reactive state variable
In the <script setup> block, import ref from 'vue' and create a reactive variable called count initialized to 0.
Vue
Need a hint?

Use ref(0) to create a reactive variable named count.

2
Create action functions to modify the state
Add two functions inside the <script setup> block: increment that adds 1 to count.value and decrement that subtracts 1 from count.value.
Vue
Need a hint?

Define two functions that change count.value by adding or subtracting 1.

3
Add buttons to call the action functions
In the template, add two buttons below the count display. The first button calls increment on click, and the second button calls decrement on click.
Vue
Need a hint?

Use @click="increment" and @click="decrement" on the buttons.

4
Add accessibility and finalize the component
Add aria-label attributes to both buttons for accessibility. The increase button should have aria-label="Increase count" and the decrease button should have aria-label="Decrease count".
Vue
Need a hint?

Use aria-label attributes on buttons to describe their actions for screen readers.