Vue项目ref变量无法读取localStorage数组数据的问题
问题解决
你的问题根源在notes的初始化逻辑上:
const notes = ref([] || JSON.parse(localStorage.getItem("notes")));
JavaScript里,空数组[]属于真值(所有对象类型的布尔转换结果都是true),所以[] || xxx永远会取前面的[],完全不会执行后面的JSON.parse(localStorage.getItem("notes")),这就导致哪怕localStorage里有数据,notes初始值还是空数组。
修正方案:
- 正确初始化notes
先尝试从localStorage读取数据,判断读取结果是否有效,无效就用空数组:
// 先获取localStorage数据,处理null的情况 const savedNotes = localStorage.getItem("notes"); // 如果savedNotes存在就解析,否则用空数组 const notes = ref(savedNotes ? JSON.parse(savedNotes) : []);
- 修正localStorage存储的问题
你当前用了notes._rawValue,这是Vue内部的私有属性,不应该直接访问。正确的做法是使用notes.value来获取ref的实际值:
const addNotesToLocalStorage = () => { localStorage.setItem("notes", JSON.stringify(notes.value)); };
(这里也可以去掉参数,直接用外部的notes变量,更简洁)
- 可选:添加异常处理
如果localStorage里的数据格式损坏,JSON.parse会抛出错误,建议加个try-catch:
const savedNotes = localStorage.getItem("notes"); let initialNotes = []; if (savedNotes) { try { initialNotes = JSON.parse(savedNotes); } catch (e) { console.error("解析本地存储数据失败", e); // 解析失败清空损坏的数据 localStorage.removeItem("notes"); } } const notes = ref(initialNotes);
修正后的完整代码片段:
<script setup> import { ref } from "vue"; const newNote = ref(""); // 修正初始化逻辑 const savedNotes = localStorage.getItem("notes"); let initialNotes = []; if (savedNotes) { try { initialNotes = JSON.parse(savedNotes); } catch (e) { console.error("解析本地存储数据失败", e); localStorage.removeItem("notes"); } } const notes = ref(initialNotes); const addNote = () => { notes.value.push({ id: Math.floor(Math.random() * 100000), text: newNote.value, date: new Date(), bgColor: getRandomColor(), }); newNote.value = ""; addNotesToLocalStorage(); }; // 修正存储逻辑,去掉私有属性访问 const addNotesToLocalStorage = () => { localStorage.setItem("notes", JSON.stringify(notes.value)); }; function getRandomColor() { return "hsl(" + Math.random() * 360 + ", 100% ,75%, 100%)"; } </script>
内容的提问来源于stack exchange,提问作者mofarih-dev
相关产品推荐
相关产品推荐

