Pinia listen state change example
Pinia
export const initData = function () {
const instance = useCounterStore()
// listen on change, then save to localStorage
instance.$subscribe((mutation, state) => {
localStorage.setItem(instance.$id, JSON.stringify(state))
})
// load from localStorage
let data = localStorage.getItem(instance.$id);
if (data) {
instance.$patch({
...JSON.parse(data)
})
}
}
Then in main.ts, after app created, call this initData
function:
import { initData } from './store/Counter'
...
app.use(createPinia)
app.mount('#app')
initData()