์์ฑ: 2026-03-04 05:39:06์์ : 2026-03-04 05:39:06
Nuxt ๋์๋ณด๋ ํ๋ก์ ํธ ์๋ฆฌ์ฆ (3): Pinia๋ฅผ ์ด์ฉํ ์ํ ๊ด๋ฆฌ ์ค๊ณ
๋์๋ณด๋์์๋ ์ฌ์ด๋๋ฐ์ ์ ํ ์ํ๋ ํ์ฌ ๋ก๊ทธ์ธํ ์ฌ์ฉ์์ ์ ๋ณด๊ฐ ์ฌ๋ฌ ์ปดํฌ๋ํธ์์ ๊ณต์ ๋์ด์ผ ํฉ๋๋ค. Pinia๋ฅผ ์ฌ์ฉํ์ฌ ๊น๋ํ๊ณ ํ์ ์์ ํ ์ํ ๊ด๋ฆฌ ํ๊ฒฝ์ ๊ตฌ์ถํด ๋ณด๊ฒ ์ต๋๋ค.
1. ์ ์ญ UI ์ํ ๊ด๋ฆฌ (App Store)
์ฌ์ด๋๋ฐ์ ์ํ๋ฅผ ๊ด๋ฆฌํ๋ ๊ฐ๋จํ ์คํ ์ด๋ฅผ ๋ง๋ญ๋๋ค.
// stores/app.ts
import { defineStore } from 'pinia'
export const useAppStore = defineStore('app', () => {
// ์ํ (State)
const isSidebarCollapsed = ref(false)
const theme = ref<'light' | 'dark'>('light')
// ์ก์
(Actions)
function toggleSidebar() {
isSidebarCollapsed.value = !isSidebarCollapsed.value
}
function toggleTheme() {
theme.value = theme.value === 'light' ? 'dark' : 'light'
}
return { isSidebarCollapsed, theme, toggleSidebar, toggleTheme }
})2. ์ฌ์ฉ์ ์ธ์ฆ ์ ๋ณด ๊ด๋ฆฌ (Auth Store)
์ฌ์ฉ์์ ํ๋กํ ์ ๋ณด๋ฅผ ๋ด๋ ์คํ ์ด์ ๋๋ค.
// stores/auth.ts
export const useAuthStore = defineStore('auth', () => {
const user = ref({
name: '๊ด๋ฆฌ์',
role: 'ADMIN',
avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Admin'
})
const isLoggedIn = computed(() => !!user.value)
return { user, isLoggedIn }
})3. ์ปดํฌ๋ํธ์์ ์ฌ์ฉํ๊ธฐ
Setup ๋ฌธ๋ฒ์ ์ฌ์ฉํ์ฌ ์ง๊ด์ ์ผ๋ก ์ํ๋ฅผ ๊ฐ์ ธ์ต๋๋ค.
<script setup>
import { useAppStore } from '@/stores/app'
const appStore = useAppStore()
</script>
<template>
<button @click="appStore.toggleSidebar">
{{ appStore.isSidebarCollapsed ? '์ด๊ธฐ' : '๋ซ๊ธฐ' }}
</button>
</template>4. Pinia ์ค๊ณ ํ
- ๋ชจ๋ํ: ํ๋์ ํฐ ์คํ ์ด๋ณด๋ค๋
app,auth,project๋ฑ ๊ด์ฌ์ฌ๋ณ๋ก ์คํ ์ด๋ฅผ ๋๋์ธ์. - SSR ๊ณ ๋ ค: Nuxt์์ Pinia๋ฅผ ์ธ ๋๋ ์๋ฒ์์๋ ์ํ๊ฐ ์ ์ง๋๋๋ก
@pinia/nuxt์ค์ ์ ํ์ธํด์ผ ํฉ๋๋ค. - Persistence: ์ํ๋ฅผ ์๋ก๊ณ ์นจ ํ์๋ ์ ์งํ๊ณ ์ถ๋ค๋ฉด
pinia-plugin-persistedstate๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ถ๊ฐํด ๋ณด์ธ์.
5. ๊ฒฐ๋ก
์ํ ๊ด๋ฆฌ ์์คํ ์ด ์ค๋น๋์์ต๋๋ค. ์ด์ ์ด ์ํ๋ค์ ์๊ฐ์ ์ผ๋ก ๋ณด์ฌ์ค ๋์๋ณด๋ ๋ ์ด์์์ ์ค์ ๋ก ์ฝ๋ฉํด ๋ณผ ์๊ฐ์ ๋๋ค.