VueJs 使用推送在 LocalStorage 中插入数据数组

问题描述

为了解释我的问题,我想制作一个小游戏,我们必须在给定时间内尽可能多地点击某个点。问题是我想制作一个可以显示所有旧结果的列表。我向你展示了这个世界的代码......(用 JSON 更新)

我的 VueJs(前):

<div class="resultat">
   <p v-for="resultat in resultats" :key="resultat">{{ resultat}}</p>
</div>

我的 VueJs(返回):

data() {
    return {
      clique: 0,resultats: [JSON.parse(localStorage.getItem("resultat"))],};
  },methods: {
onTimesUp() {
    this.resultats.push(this.clique)
    localStorage.setItem("resultat",JSON.stringify(this.resultats));
  }
}

尝试4次后的结果是:[ [ [ [ null,6 ],7 ],3 ],5 ]

我想要:[6,7,3,5]

请帮助我,我尝试了 2 天...

解决方法

您需要将其存储为字符串,因此您需要使用 JSON 存储它(JSON 是一种将 Javascript 数据序列化/反序列化为字符串的方法):

localStorage.setItem("resultat",JSON.stringify(this.resultats) );

message: JSON.parse(localStorage.getItem("resultat")),

有关 JSON 的更多信息,请参见此处:https://www.w3schools.com/js/js_json.asp

,

主要问题是您存储一组项目,然后加载您将数组放入数组中:resultats: [JSON.parse(localStorage.getItem("resultat"))],

去除包装 []

尽管就个人而言,将数据作为声明保持干净比使用 before 呈现生命周期钩子填充它更好,即创建 beforeMount。

同样在没有分数的初始加载 localStorage.getItem("resultat") 将返回 null,导致您的数组变为 null。对其进行检查或简单地执行 || '[]'

  data() {
    return {
      clique: 0,resultats: []
    };
  },created() {
     this.resultats = JSON.parse(localStorage.getItem("resultat") || '[]')
  },methods: {
    onTimesUp() {
      this.resultats.push(this.clique)
      localStorage.setItem("resultat",JSON.stringify(this.resultats));
    }
  }