0
0
Vueframework~30 mins

Why state management is needed in Vue - See It in Action

Choose your learning style9 modes available
Why State Management is Needed in Vue
📖 Scenario: You are building a simple Vue app that shows a list of tasks and a counter of how many tasks are done. You want to keep track of the tasks and their done status in one place so all parts of the app can see the same data.
🎯 Goal: Build a small Vue app that uses a shared state object to hold tasks and their done status. Show the tasks and a count of done tasks. This will demonstrate why state management is needed to keep data consistent across components.
📋 What You'll Learn
Create a reactive state object with a list of tasks and their done status
Create a computed property to count how many tasks are done
Display the list of tasks with checkboxes to toggle done status
Display the count of done tasks updating automatically
💡 Why This Matters
🌍 Real World
Many apps need to keep data consistent across different parts of the interface. State management helps by storing data in one place and letting all components react to changes.
💼 Career
Understanding state management is key for frontend developers working with Vue or other frameworks. It helps build apps that are easier to maintain and less buggy.
Progress0 / 4 steps
1
Set up the tasks state
Create a reactive state object called state with a property tasks that is an array of three objects. Each object should have id, title, and done properties. Use these exact tasks: {id: 1, title: 'Buy groceries', done: false}, {id: 2, title: 'Wash car', done: true}, {id: 3, title: 'Read book', done: false}.
Vue
Need a hint?

Use reactive from Vue to create a state object with a tasks array containing the exact task objects.

2
Add a computed property for done count
Import computed from 'vue' and create a computed property called doneCount that returns the number of tasks in state.tasks where done is true.
Vue
Need a hint?

Use computed to create doneCount that filters state.tasks for tasks where done is true and returns the count.

3
Display tasks with checkboxes
In the <template>, use a v-for directive to loop over state.tasks with task as the item and task.id as the key. For each task, show a checkbox bound with v-model to task.done and a label showing task.title.
Vue
Need a hint?

Use v-for to loop over state.tasks. Bind checkbox with v-model to task.done. Use label with :for attribute for accessibility.

4
Show count of done tasks
Below the task list in the <template>, add a paragraph that shows the text Done tasks: followed by the value of the computed property doneCount.
Vue
Need a hint?

Use a paragraph tag to show the text and bind the computed property doneCount inside curly braces.