我对 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。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我建议使用 Vue Use 库。它有一个非常好的模数,可以在 Vue.js 3 中将本地存储与 VueX/Pinia 一起使用。
https://view.org/core/useLocalStorage/