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

Vue项目ref变量无法读取localStorage数组数据的问题

问题解决

你的问题根源在notes的初始化逻辑上:

const notes = ref([] || JSON.parse(localStorage.getItem("notes")));

JavaScript里,空数组[]属于真值(所有对象类型的布尔转换结果都是true),所以[] || xxx永远会取前面的[],完全不会执行后面的JSON.parse(localStorage.getItem("notes")),这就导致哪怕localStorage里有数据,notes初始值还是空数组。

修正方案:

  1. 正确初始化notes
    先尝试从localStorage读取数据,判断读取结果是否有效,无效就用空数组:
// 先获取localStorage数据,处理null的情况
const savedNotes = localStorage.getItem("notes");
// 如果savedNotes存在就解析,否则用空数组
const notes = ref(savedNotes ? JSON.parse(savedNotes) : []);
  1. 修正localStorage存储的问题
    你当前用了notes._rawValue,这是Vue内部的私有属性,不应该直接访问。正确的做法是使用notes.value来获取ref的实际值:
const addNotesToLocalStorage = () => {
  localStorage.setItem("notes", JSON.stringify(notes.value));
};

(这里也可以去掉参数,直接用外部的notes变量,更简洁)

  1. 可选:添加异常处理
    如果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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 19:32:50