How to use localStorage on Vuejs3?
P粉418351692
P粉418351692 2023-10-31 23:58:20
0
1
797

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粉418351692
P粉418351692

reply all(1)
P粉709307865

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/

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template