Pinia: O Novo Vuex
Pinia é a solução oficial de gerenciamento de estado para Vue.js 3, oferecendo uma API mais simples e melhor suporte a TypeScript.
Instalação
npm install piniaCriando uma Store
// stores/user.js
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
export const useUserStore = defineStore('user', () => {
const user = ref(null);
const isAuthenticated = computed(() => !!user.value);
function setUser(userData) {
user.value = userData;
}
function logout() {
user.value = null;
}
return { user, isAuthenticated, setUser, logout };
});Usando a Store
<script setup>
import { useUserStore } from '@/stores/user';
const userStore = useUserStore();
// Acessar estado
console.log(userStore.isAuthenticated);
// Chamar ações
userStore.setUser({ name: 'John', email: 'john@example.com' });
</script>
1 comment