Vue.js course · Module 11: Pinia

Composition API Stores (setup syntax)

3 min read ·
In this lesson5

At NOVA LAB, every system has its own configuration protocol. Pinia offers two styles for defining stores - Composition API (setup function) and Options API. Pinia doesn't recommend either: Options API stores are easier to start with, while Composition API stores are more flexible and closer to how we write Vue 3 components.

Composition API vs Options API

// Composition API (setup store)
export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)
  function increment() { count.value++ }

  return { count, doubleCount, increment }
})

// Options API
export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    doubleCount: (state) => state.count * 2
  },
  actions: {
    increment() { this.count++ }
  }
})

When to Choose Which Style?

AspectComposition APIOptions API
FlexibilityFullLimited
TypeScriptNatural typingRequires declarations
$reset()Must define manuallyWorks automatically
ComposablesEasy to useMore difficult
SyntaxLike <script setup>Like Vue Options API

Using Composables in a Store

Composition API allows easy use of composables inside a store:

import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { useLocalStorage } from '@vueuse/core'

export const useSettingsStore = defineStore('settings', () => {
  // Composable inside a store!
  const theme = useLocalStorage('theme', 'dark')
  const language = useLocalStorage('language', 'en')

  const isDark = computed(() => theme.value === 'dark')

  function toggleTheme() {
    theme.value = isDark.value ? 'light' : 'dark'
  }

  return { theme, language, isDark, toggleTheme }
})

Watchers in a Store

You can use watch and watchEffect inside a store:

export const useAlertStore = defineStore('alerts', () => {
  const temperature = ref(22)
  const alerts = ref([])

  // Watcher reacting to changes
  watch(temperature, (newTemp, oldTemp) => {
    if (newTemp > 50) {
      alerts.value.push({
        type: 'critical',
        message: `Temperature critical: ${newTemp}°C`,
        timestamp: Date.now()
      })
    }
  })

  function setTemperature(value) {
    temperature.value = value
  }

  return { temperature, alerts, setTemperature }
})

Typing with TypeScript

interface CrewMember {
  id: number
  name: string
  role: 'commander' | 'engineer' | 'scientist'
  active: boolean
}

export const useCrewStore = defineStore('crew', () => {
  const members = ref<CrewMember[]>([])
  const selected = ref<CrewMember | null>(null)

  const activeMembers = computed<CrewMember[]>(() =>
    members.value.filter(m => m.active)
  )

  function addMember(member: Omit<CrewMember, 'id'>): CrewMember {
    const newMember: CrewMember = {
      ...member,
      id: Date.now()
    }
    members.value.push(newMember)
    return newMember
  }

  return { members, selected, activeMembers, addMember }
})
Code for this lesson: App.vue
<script setup>
import { ref, computed, watch } from 'vue'

// Composition API Store with watchers and TypeScript patterns
const temperature = ref(22)
const alerts = ref([])
const settings = ref({
  theme: 'dark',
  language: 'pl',
  unit: 'celsius'
})

// Watcher inside store
watch(temperature, (newTemp) => {
  if (newTemp > 45) {
    alerts.value.push({
      id: Date.now(),
      type: 'critical',
      message: `Temperature critical: ${newTemp} C`,
      time: new Date().toLocaleTimeString()
    })
  } else if (newTemp > 35) {
    alerts.value.push({
      id: Date.now(),
      type: 'warning',
      message: `Temperature high: ${newTemp} C`,
      time: new Date().toLocaleTimeString()
    })
  }
})

// Getters
const isDark = computed(() => settings.value.theme === 'dark')
const tempDisplay = computed(() => {
  if (settings.value.unit === 'fahrenheit') {
    return ((temperature.value * 9/5) + 32).toFixed(1) + ' F'
  }
  return temperature.value + ' C'
})

const criticalAlerts = computed(() =>
  alerts.value.filter(a => a.type === 'critical')
)

// Actions
function setTemperature(value) {
  temperature.value = Math.max(-100, Math.min(100, value))
}

function toggleTheme() {
  settings.value.theme = isDark.value ? 'light' : 'dark'
}

function toggleUnit() {
  settings.value.unit = settings.value.unit === 'celsius' ? 'fahrenheit' : 'celsius'
}

function dismissAlert(id) {
  alerts.value = alerts.value.filter(a => a.id !== id)
}

function clearAlerts() {
  alerts.value = []
}
</script>

<template>
  <div class="nova-lab" :class="settings.theme">
    <h1>NOVA LAB - Composition Store</h1>

    <div class="temp-control">
      <h2>Temperature Control</h2>
      <div class="temp-display" :class="{ critical: temperature > 45, warning: temperature > 35 }">
        {{ tempDisplay }}
      </div>
      <div class="slider-row">
        <button @click="setTemperature(temperature - 5)" class="btn">-5</button>
        <input type="range" v-model.number="temperature" min="-50" max="80" class="slider" />
        <button @click="setTemperature(temperature + 5)" class="btn">+5</button>
      </div>
    </div>

    <div class="settings-panel">
      <h2>Settings (composable pattern)</h2>
      <button @click="toggleTheme" class="btn">
        Theme: {{ settings.theme }}
      </button>
      <button @click="toggleUnit" class="btn">
        Unit: {{ settings.unit }}
      </button>
    </div>

    <div v-if="alerts.length" class="alerts-panel">
      <div class="alerts-header">
        <h2>Alerts ({{ alerts.length }})</h2>
        <button @click="clearAlerts" class="btn btn-sm">Clear All</button>
      </div>
      <div v-for="alert in alerts" :key="alert.id"
        class="alert-item" :class="alert.type">
        <span>{{ alert.time }} - {{ alert.message }}</span>
        <button @click="dismissAlert(alert.id)" class="dismiss">x</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.nova-lab {
  min-height: 100vh;
  padding: 20px;
  font-family: monospace;
  transition: all 0.3s;
}
.nova-lab.dark { background: #0a0e27; color: #00ff88; }
.nova-lab.light { background: #f0f4f8; color: #1a1e3f; }
h1 { margin-bottom: 20px; text-align: center; }
h2 { color: #00b4d8; margin-bottom: 10px; }
.temp-control, .settings-panel, .alerts-panel {
  max-width: 500px;
  margin: 0 auto 15px;
  padding: 15px;
  border: 2px solid #00b4d8;
  background: rgba(0, 180, 216, 0.1);
}
.temp-display {
  text-align: center;
  font-size: 2em;
  font-weight: bold;
  margin: 10px 0;
}
.temp-display.warning { color: #ff9900; }
.temp-display.critical { color: #ff4444; }
.slider-row { display: flex; align-items: center; gap: 10px; }
.slider { flex: 1; }
.btn {
  background: #00b4d8;
  color: #0a0e27;
  border: none;
  padding: 6px 14px;
  cursor: pointer;
  font-family: monospace;
  margin: 2px;
}
.btn:hover { background: #00ff88; }
.btn-sm { padding: 4px 10px; font-size: 0.85em; }
.alerts-header { display: flex; justify-content: space-between; align-items: center; }
.alert-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  margin: 5px 0;
  border: 1px solid;
}
.alert-item.warning { border-color: #ff9900; color: #ff9900; }
.alert-item.critical { border-color: #ff4444; color: #ff4444; }
.dismiss {
  background: none;
  border: 1px solid currentColor;
  color: inherit;
  cursor: pointer;
  padding: 2px 6px;
  font-family: monospace;
}
</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. 1. What is the main difference between a Composition API and Options API store in Pinia?

  2. 2. Can you use watch() inside a Composition API store?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Vertical ordering

    Arrange the elements of a Composition API store in the correct order

  • Code editor

    Define a settings store with theme, language, an isDark getter and a toggleTheme action.

  • Horizontal ordering

    Arrange the elements to type a store with TypeScript

  • Code editor

    Define a crew store with getters, actions and a custom $reset.

  1. QuestionComposition vs Options API
  2. Put in orderStore Elements in Composition API
  3. Coding taskPractice: Settings Store
  4. QuestionWatchers in a Store
  5. Put in orderTypeScript in a Store
  6. Question$reset in Composition API
  7. Coding taskPractice: Complete Crew Store

Useful articles