Vue.js course Β· Module 11: Pinia
Store Composition
In this lesson3
At NOVA LAB, different station systems must work together - the oxygen system communicates with the alarm system, and the navigation system with the communication system. Similarly in Pinia - stores can import and use other stores.
Store Using Another Store
// stores/auth.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useAuthStore = defineStore('auth', () => {
const user = ref(null)
const token = ref(null)
const isAuthenticated = computed(() => !!token.value)
const userName = computed(() => user.value?.name || 'Guest')
async function login(credentials) {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(credentials)
})
const data = await res.json()
token.value = data.token
user.value = data.user
}
function logout() {
user.value = null
token.value = null
}
return { user, token, isAuthenticated, userName, login, logout }
})// stores/missions.js - uses auth store
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useAuthStore } from './auth'
export const useMissionsStore = defineStore('missions', () => {
const missions = ref([])
async function fetchMissions() {
// Use auth store to get the token
const authStore = useAuthStore()
if (!authStore.isAuthenticated) {
throw new Error('Must be logged in')
}
const res = await fetch('/api/missions', {
headers: {
'Authorization': `Bearer ${authStore.token}`
}
})
missions.value = await res.json()
}
return { missions, fetchMissions }
})Mutual Store Dependencies
Stores can use each other, but call useStore() inside actions (not at the top of the setup function) to avoid circular dependency issues:
// stores/notifications.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useNotificationStore = defineStore('notifications', () => {
const notifications = ref([])
function add(message, type = 'info') {
notifications.value.push({
id: Date.now(),
message,
type,
timestamp: new Date()
})
}
function remove(id) {
notifications.value = notifications.value.filter(n => n.id !== id)
}
return { notifications, add, remove }
})
// stores/resources.js - uses notifications
import { useNotificationStore } from './notifications'
export const useResourceStore = defineStore('resources', () => {
const oxygen = ref(100)
function consumeOxygen(amount) {
oxygen.value -= amount
if (oxygen.value < 20) {
// Call useStore INSIDE action
const notifStore = useNotificationStore()
notifStore.add('Oxygen level critical!', 'danger')
}
}
return { oxygen, consumeOxygen }
})Multi-Store Architecture
It's recommended to create many small, specialized stores instead of one large one:
stores/
βββ auth.js # User authorization
βββ resources.js # Station resources (oxygen, water, energy)
βββ crew.js # Crew data
βββ missions.js # Missions and tasks
βββ notifications.js # Notification system
βββ settings.js # Application settingsEach store is responsible for one "module" of the application - just as each NOVA LAB station module has its own function.
Code for this lesson: App.vue
<script setup>
import { ref, computed } from 'vue'
// Store composition - AuthStore
const user = ref({ name: 'Commander Nova', role: 'admin' })
const token = ref('jwt-token-xyz')
const isAuthenticated = computed(() => !!token.value)
// Store composition - ResourceStore (uses AuthStore)
const resources = ref([
{ id: 1, name: 'Oxygen', level: 92, unit: '%' },
{ id: 2, name: 'Water', level: 78, unit: '%' },
{ id: 3, name: 'Energy', level: 65, unit: '%' }
])
// Store composition - NotificationStore
const notifications = ref([])
function addNotification(message, type = 'info') {
const id = Date.now()
notifications.value.push({ id, message, type, time: new Date().toLocaleTimeString() })
setTimeout(() => {
notifications.value = notifications.value.filter(n => n.id !== id)
}, 4000)
}
// ResourceStore actions use NotificationStore
function consumeResource(id, amount) {
const resource = resources.value.find(r => r.id === id)
if (!resource) return
resource.level = Math.max(0, resource.level - amount)
if (resource.level < 20) {
// Cross-store: resource -> notification
addNotification(`${resource.name} critically low: ${resource.level}${resource.unit}!`, 'danger')
} else if (resource.level < 50) {
addNotification(`${resource.name} below 50%: ${resource.level}${resource.unit}`, 'warning')
}
}
function refillResource(id) {
const resource = resources.value.find(r => r.id === id)
if (resource) {
resource.level = 100
addNotification(`${resource.name} refilled to 100%`, 'success')
}
}
// Cross-store getter
const criticalResources = computed(() =>
resources.value.filter(r => r.level < 30)
)
</script>
<template>
<div class="nova-lab">
<h1>NOVA LAB - Store Composition</h1>
<div class="user-bar" v-if="isAuthenticated">
Logged in: {{ user.name }} ({{ user.role }})
</div>
<div class="resources-grid">
<div v-for="r in resources" :key="r.id"
class="resource-card" :class="{ critical: r.level < 20, warning: r.level < 50 }">
<h3>{{ r.name }}</h3>
<div class="level-bar">
<div class="level-fill" :style="{ width: r.level + '%' }"></div>
</div>
<div class="level-text">{{ r.level }}{{ r.unit }}</div>
<div class="r-actions">
<button @click="consumeResource(r.id, 15)" class="btn">-15</button>
<button @click="refillResource(r.id)" class="btn btn-green">Refill</button>
</div>
</div>
</div>
<div v-if="criticalResources.length" class="critical-alert">
CRITICAL: {{ criticalResources.map(r => r.name).join(', ') }}
</div>
<div class="notifications">
<div v-for="n in notifications" :key="n.id" class="notif" :class="n.type">
{{ n.time }} - {{ n.message }}
</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: 15px; text-align: center; }
.user-bar {
text-align: center;
padding: 8px;
background: rgba(0, 180, 216, 0.1);
border: 1px solid #00b4d8;
margin-bottom: 15px;
color: #00b4d8;
}
.resources-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 15px; }
.resource-card {
background: rgba(0, 255, 136, 0.05);
border: 2px solid #00ff88;
padding: 15px;
text-align: center;
}
.resource-card.warning { border-color: #ff9900; }
.resource-card.critical { border-color: #ff4444; background: rgba(255, 68, 68, 0.1); }
h3 { color: #00b4d8; margin-bottom: 8px; }
.level-bar { height: 12px; background: #1a1e3f; border: 1px solid #00b4d8; margin: 8px 0; }
.level-fill { height: 100%; background: #00ff88; transition: width 0.3s; }
.resource-card.warning .level-fill { background: #ff9900; }
.resource-card.critical .level-fill { background: #ff4444; }
.level-text { font-size: 1.2em; font-weight: bold; margin-bottom: 8px; }
.r-actions { display: flex; gap: 5px; justify-content: center; }
.btn {
background: #00b4d8;
color: #0a0e27;
border: none;
padding: 5px 12px;
cursor: pointer;
font-family: monospace;
}
.btn-green { background: #00ff88; }
.critical-alert {
padding: 10px;
background: rgba(255, 68, 68, 0.2);
border: 2px solid #ff4444;
color: #ff4444;
text-align: center;
margin-bottom: 15px;
font-weight: bold;
}
.notifications { max-width: 500px; margin: 0 auto; }
.notif {
padding: 8px;
margin: 4px 0;
border: 1px solid;
font-size: 0.9em;
}
.notif.info { border-color: #00b4d8; color: #00b4d8; }
.notif.warning { border-color: #ff9900; color: #ff9900; }
.notif.danger { border-color: #ff4444; color: #ff4444; }
.notif.success { border-color: #00ff88; color: #00ff88; }
</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 can one Pinia store use another store?
2. Where should useStore() be called when using stores in other stores?
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 'tasks' store that uses the auth store - fetchTasks checks isAuthenticated.
- Vertical ordering
Arrange the layers of multi-store architecture
- Click in order
Arrange the elements to call an action from another store
- Code editor
Create a resource store with alerts - consume generates alerts when the level is low.