Pinia is the official state management solution for Vue 3. It provides a simple, intuitive API built on top of the Composition API, with excellent TypeScript inference and Vue DevTools support.
npm install pinia
// main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
createApp(App).use(createPinia()).mount('#app')
// stores/auth.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useAuthStore = defineStore('auth', () => {
const user = ref(null)
const token = ref(localStorage.getItem('token'))
const isLoggedIn = computed(() => !!token.value)
async function login(credentials) {
const res = await fetch('/api/login', { method: 'POST', body: JSON.stringify(credentials) })
const data = await res.json()
user.value = data.user
token.value = data.token
localStorage.setItem('token', data.token)
}
function logout() {
user.value = null
token.value = null
localStorage.removeItem('token')
}
return { user, token, isLoggedIn, login, logout }
})
<script setup>
import { useAuthStore } from '@/stores/auth'
const auth = useAuthStore()
</script>
<template>
<div v-if="auth.isLoggedIn">
Welcome, {{ auth.user.name }}
<button @click="auth.logout">Logout</button>
</div>
<LoginForm v-else @submit="auth.login" />
</template>
npm install pinia-plugin-persistedstate
import { createPinia } from 'pinia'
import piniaPersistedState from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPersistedState)
// In your store
export const useAuthStore = defineStore('auth', () => { ... }, {
persist: true, // persists to localStorage automatically
})
All Comments