You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中localStorage使用问题:Statistic.vue数据显示滞后1位

问题:localStorage更新后Statistic.vue数据滞后显示

我在使用localStorage时遇到问题:Statistic.vue组件的模态框中,numberOfGames仅在页面加载时显示正确数值,后续更新会始终滞后1位。相关代码如下:

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>

store/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仅在组件初始化时从localStorage读取一次,后续localStorage更新后,组件没有监听变化的机制,无法自动同步最新值,导致显示滞后。同时Vuex的mutation仅更新localStorage,未通知组件同步数据。

解决方案

方案1:监听localStorage存储事件

在Statistic.vue中添加storage事件监听,实时同步最新值:

<template>
  <p class='modal'>{{ numberOfGames }}</p>
</template>

<script>
export default {
  name: "GameStatistic",
  data() {
    return {
      numberOfGames: localStorage.getItem("NumberOfGames") || '0'
    } 
  },
  mounted() {
    window.addEventListener('storage', this.updateGameCount);
    // 初始化时确保值正确
    this.updateGameCount();
  },
  beforeUnmount() {
    window.removeEventListener('storage', this.updateGameCount);
  },
  methods: {
    updateGameCount() {
      const count = localStorage.getItem("NumberOfGames");
      this.numberOfGames = count ? count : '0';
    }
  }
}
</script>

方案2:用Vuex状态同步(推荐,符合Vue数据流)

将游戏计数放到Vuex状态中,组件直接从state取值,自动响应变化:

  1. 更新store/index.js:
export default createStore({
  state: {
    currentGuessIndex: 0,
    isWinner: false,
    numberOfGames: parseInt(localStorage.getItem("NumberOfGames")) || 0
  },
  mutations: {
    checkNumberOfGames(state) {
      if (state.numberOfGames === 0) {
          state.numberOfGames = 1;
      } else if (state.currentGuessIndex >= 6 || state.isWinner) {
          state.numberOfGames += 1;
      }
      // 同步到localStorage持久化
      localStorage.setItem("NumberOfGames", state.numberOfGames.toString());
    },
    initGameCount(state) {
      const count = localStorage.getItem("NumberOfGames");
      state.numberOfGames = count ? parseInt(count) : 0;
    }
  },
  actions: {},
  modules: {}
})
  1. 修改Statistic.vue:
<template>
  <p class='modal'>{{ numberOfGames }}</p>
</template>

<script>
import { mapState } from 'vuex';

export default {
  name: "GameStatistic",
  computed: {
    ...mapState(['numberOfGames'])
  },
  mounted() {
    this.$store.commit('initGameCount');
  }
}
</script>

额外提示

  • 注意类型转换:localStorage存储的是字符串,读取时务必转为数字,避免出现字符串拼接错误(如"1"+1变成"11")。
  • 检查mutation触发条件:确保checkNumberOfGames的触发时机和判断逻辑符合业务需求,避免漏更新计数。

内容的提问来源于stack exchange,提问作者mirodil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 15:48:47