搜尋

首頁  >  問答  >  主體

如何在Vuejs3上使用localStorage?

我對 localStorage 及其使用有點困惑。我有一個 comonent Statistic.vue ,它在最後顯示模態。

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')
   }
}

我的問題是 Statistic.vue 中的 numberOfGames 未顯示正確的數字,載入頁面後它會顯示正確的值,否則會留下 1。

P粉418351692P粉418351692463 天前801

全部回覆(1)我來回復

  • P粉709307865

    P粉7093078652023-11-01 12:51:46

    我建議使用 Vue Use 函式庫。它有一個非常好的模數,可以在 Vue.js 3 中將本地儲存與 VueX/Pinia 一起使用。

    https://view.org/core/useLocalStorage/

    回覆
    0
  • 取消回覆