Gestire gli state in Vue.js con Pinia
Pinia è una libreria per gestire gli state in Vue.js.
In questo articolo vediamo come usarla per salvare gli state anche nello storage.
Prima di tutto dobbiamo installare due librerie; possiamo usare npm:
npm install pinia pinia-plugin-persistedstate
Poi il main.js:
import {createApp} from 'vue';
import {createPinia} from 'pinia';
import App from './App.vue';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
createApp(App)
.use(pinia)
.mount('#app');
Poi ho creato un file per lo store stores/counter.js:
import {defineStore} from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++
},
},
persist: {
storage: sessionStorage,
},
});
Infine il componente:
<script setup>
import {useCounterStore} from '@/stores/counter'
const counter = useCounterStore()
</script>
<template>
<div>
<div>Current Count: {{ counter.count }}</div>
<button @click="counter.increment">Incrementa</button>
</div>
</template>
<style scoped>
button {
margin-top: 8px;
padding: 6px 12px;
border: none;
background-color: #42b983;
color: white;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #36936a;
}
</style>
Enjoy!
javascript vuejs pinia
Commentami!