Vue.js course ยท Module 11: Pinia
State in Pinia
In this lesson5
State is reactive data stored in the store - like the main computer's database at NOVA LAB. Every sensor reading, every mission parameter is recorded here and available to all station modules.
Defining State
In Composition API style, state is simply ref() and reactive():
import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
export const useResourceStore = defineStore('resources', () => {
// Simple values - ref()
const oxygen = ref(98.5)
const water = ref(1250)
const energy = ref(87)
const isEmergency = ref(false)
// Objects - reactive() or ref()
const crew = reactive({
commander: 'Nova',
engineer: 'Atlas',
scientist: 'Darwin'
})
// Arrays
const logs = ref([])
return { oxygen, water, energy, isEmergency, crew, logs }
})Modifying State
State can be modified directly in actions or from a component:
export const useResourceStore = defineStore('resources', () => {
const oxygen = ref(98.5)
// Action modifies state
function consumeOxygen(amount) {
oxygen.value = Math.max(0, oxygen.value - amount)
}
return { oxygen, consumeOxygen }
})<script setup>
const store = useResourceStore()
// Direct modification (works, but actions are better)
store.oxygen = 95.0
// Through action (recommended)
store.consumeOxygen(3.5)
</script>$patch - Updating Multiple Properties
$patch allows updating multiple state properties at once - more efficient than modifying one at a time:
const store = useResourceStore()
// Object patch - simple override
store.$patch({
oxygen: 95.0,
water: 1200,
energy: 82,
isEmergency: false
})
// Function patch - for complex operations
store.$patch((state) => {
state.oxygen -= 3.5
state.logs.push({
type: 'consumption',
timestamp: Date.now()
})
})$reset - Restoring Initial State
In Options API style $reset() works automatically. In Composition API you must define your own reset function:
export const useResourceStore = defineStore('resources', () => {
const oxygen = ref(100)
const water = ref(1500)
const energy = ref(100)
// Custom reset for Composition API
function $reset() {
oxygen.value = 100
water.value = 1500
energy.value = 100
}
return { oxygen, water, energy, $reset }
})
// Usage
const store = useResourceStore()
store.$reset() // Restores initial values$state - Accessing the Entire State
const store = useResourceStore()
// Read entire state
const snapshot = store.$state
// Override entire state
store.$state = {
oxygen: 100,
water: 1500,
energy: 100,
isEmergency: false,
crew: { commander: 'Nova' },
logs: []
}Code for this lesson: App.vue
<script setup>
import { ref, computed } from 'vue'
// Resource Store simulation
const oxygen = ref(98.5)
const water = ref(1250)
const energy = ref(87)
const logs = ref([])
// Getters
const oxygenStatus = computed(() => oxygen.value > 50 ? 'OK' : 'LOW')
const waterStatus = computed(() => water.value > 500 ? 'OK' : 'LOW')
const energyStatus = computed(() => energy.value > 40 ? 'OK' : 'LOW')
// Actions
function consumeOxygen(amount) {
oxygen.value = Math.max(0, +(oxygen.value - amount).toFixed(1))
addLog('Oxygen consumed: -' + amount + '%')
}
function consumeWater(amount) {
water.value = Math.max(0, water.value - amount)
addLog('Water consumed: -' + amount + 'L')
}
function consumeEnergy(amount) {
energy.value = Math.max(0, energy.value - amount)
addLog('Energy consumed: -' + amount + '%')
}
function addLog(message) {
logs.value.unshift({
message,
time: new Date().toLocaleTimeString()
})
if (logs.value.length > 8) logs.value.pop()
}
// $patch simulation
function patchResources(updates) {
if (updates.oxygen !== undefined) oxygen.value = updates.oxygen
if (updates.water !== undefined) water.value = updates.water
if (updates.energy !== undefined) energy.value = updates.energy
addLog('Resources patched')
}
function resetResources() {
oxygen.value = 100
water.value = 1500
energy.value = 100
logs.value = []
}
</script>
<template>
<div class="nova-lab">
<h1>NOVA LAB - State Management</h1>
<div class="grid">
<div class="resource-panel">
<h2>Resources</h2>
<div class="resource" v-for="r in [
{ name: 'Oxygen', value: oxygen, unit: '%', status: oxygenStatus, action: () => consumeOxygen(5) },
{ name: 'Water', value: water, unit: 'L', status: waterStatus, action: () => consumeWater(50) },
{ name: 'Energy', value: energy, unit: '%', status: energyStatus, action: () => consumeEnergy(10) }
]" :key="r.name">
<div class="r-header">
<span>{{ r.name }}</span>
<span :class="r.status.toLowerCase()">{{ r.status }}</span>
</div>
<div class="r-value">{{ r.value }}{{ r.unit }}</div>
<button @click="r.action" class="btn-sm">Consume</button>
</div>
<div class="btn-group">
<button @click="patchResources({ oxygen: 50, water: 800 })" class="btn">
$patch (O2=50, H2O=800)
</button>
<button @click="resetResources" class="btn btn-reset">
$reset
</button>
</div>
</div>
<div class="log-panel">
<h2>Activity Log</h2>
<div v-for="(log, i) in logs" :key="i" class="log-entry">
<span class="log-time">{{ log.time }}</span>
{{ log.message }}
</div>
<p v-if="!logs.length" class="empty">No activity yet...</p>
</div>
</div>
</div>
</template>
<style scoped>
.nova-lab {
background: #0a0e27;
color: #00ff88;
min-height: 100vh;
padding: 20px;
font-family: monospace;
}
h1 { color: #00ff88; margin-bottom: 20px; text-align: center; }
h2 { color: #00b4d8; margin-bottom: 15px; }
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; max-width: 700px; margin: 0 auto; }
.resource-panel, .log-panel {
background: rgba(0, 180, 216, 0.1);
border: 2px solid #00b4d8;
padding: 15px;
}
.resource {
background: rgba(0, 255, 136, 0.05);
border: 1px solid #00ff88;
padding: 10px;
margin-bottom: 8px;
}
.r-header { display: flex; justify-content: space-between; margin-bottom: 5px; }
.r-value { font-size: 1.2em; font-weight: bold; margin-bottom: 5px; }
.ok { color: #00ff88; }
.low { color: #ff4444; }
.btn-sm {
background: #00b4d8;
color: #0a0e27;
border: none;
padding: 4px 12px;
cursor: pointer;
font-family: monospace;
}
.btn-group { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; }
.btn {
background: #00b4d8;
color: #0a0e27;
border: none;
padding: 8px 12px;
cursor: pointer;
font-family: monospace;
font-size: 0.85em;
}
.btn:hover { background: #00ff88; }
.btn-reset { background: #ff9900; }
.log-entry {
padding: 5px 0;
border-bottom: 1px solid rgba(0, 180, 216, 0.3);
font-size: 0.85em;
}
.log-time { color: #00b4d8; margin-right: 8px; }
.empty { color: #666; font-style: italic; }
</style>Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How is state defined in a Pinia store (Options API)?
2. What does the $patch method do in Pinia?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Create a store with ref() state, a consumeOxygen action and a patchResources action.
- Vertical ordering
Arrange the steps for configuring Pinia in a Vue application
- Click in order
Arrange the elements to correctly use storeToRefs
- Code editor
Create patchUpdate (sets values) and patchFunction (reduces values by 10%).