如何在Vuejs3上使用localStorage?
P粉418351692
P粉418351692 2023-10-31 23:58:20

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

全部回覆(1)
P粉709307865

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

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

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!