I'm a little confused about localStorage and its usage. I have a comonent Statistic.vue which displays modal at the end.
Statistic.vue
<template> <p class='modal'>{{numberOfGames}}<p> <template/> <script> export default { name: "GameStatistic", data() { return { numberOfGames: localStorage.getItem("NumberOfGames") } }, mounted() { //this.$store.commit('checkNumberOfGames') }, } </script>
index.js
export default createStore({ state: { currentGuessIndex: 0, isWinner: false }, mutations: { checkNumberOfGames(state) { if (localStorage.getItem("NumberOfGames") === null) { localStorage.setItem("NumberOfGames", 1) } else if (state.currentGuessIndex >= 6 || state.isWinner) { let counter = localStorage.getItem("NumberOfGames"); localStorage.setItem("NumberOfGames", parseInt(counter)+1) } } }, actions: { }, modules: { } })
WordRow.vue
// some stuff watch: { submitted: { async handler(submitted) { //some stuff this.$store.commit('checkNumberOfGames') } }
My problem is that the numberOfGames in Statistic.vue
is not showing the correct number, after loading the page it shows the correct value otherwise it leaves 1.
P粉7093078652023-11-01 12:51:46
I recommend using the Vue Use library. It has a very good modulus for using local storage with VueX/Pinia in Vue.js 3.
https://view.org/core/useLocalStorage/