Home > Back-end >  How to use localStorage on Vuejs3?
How to use localStorage on Vuejs3?

Time:08-24

I am a bit confused about localStorage and using it. I have a copmonent Statistic.vue which shows 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 question is that numberOfGames in Statistic.vue not showing correct number, alfter loading page it shows correct value otherwise it lefts behind by 1.

CodePudding user response:

I recommend using the Vue Use library. It has o pretty nice modulo for using Local Storage with VueX/Pinia in Vue.js 3.

https://vueuse.org/core/useLocalStorage/

CodePudding user response:

localStorage is meant only for persisting state across refreshes, it doesn't natively work with Vue's reactivity. Instead you can save numberOfGames as part of your vuex state and set your data variable to that. You can still initialize the store variable with the localStorage number.

  • Related