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

Vue3组合式API:从localStorage取数据在homePosts组件显示失败求助

问题排查:Vue3博客项目无法展示localStorage中的文章内容

一、writePost.vue 存在的问题及修复

1. 表单提交未阻止默认行为

点击submit按钮会触发表单默认提交,导致页面刷新,中断数据存储流程。需修改按钮类型并移除内部嵌套的router-link,避免提前跳转。

2. localStorage存储数据格式错误

addLocalStorage方法传入的是ref响应式对象而非实际数组,JSON.stringify后会生成包含Vue内部属性的无效字符串,无法正确解析。

3. 路由跳转逻辑不合理

嵌套的router-link会直接触发跳转,可能在数据存入localStorage前就跳转到列表页,导致数据未同步。需在数据存储完成后手动调用路由跳转。

修改后的writePost.vue代码:

<template>
  <div>
    <form class="form">
      <label for="writer">Writer name: </label>
      <input v-model="newWriter" type="text" max="500" />
      <br />
      <label for="img">Select image:</label>
      <input type="file" id="img" name="img" accept="image/*" />
      <br />
      <label for="headline">Headline </label>
      <input v-model="newHeadline" type="text" max="500" />
      <label>Your blogtext: </label>
      <textarea v-model="newNote" name="" id="" cols="30" rows="30"></textarea>
      <button type="button" @click="addNote" class="button">Post blog</button>
    </form>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();
const newNote = ref("");
const newWriter = ref("");
const newHeadline = ref("");
const notes = ref([]);

const addNote = () => {
  if (!newWriter.value || !newHeadline.value || !newNote.value) return;
  
  notes.value.push({
    id: Date.now() + Math.floor(Math.random() * 1000),
    text: newNote.value,
    writer: newWriter.value,
    headline: newHeadline.value,
  });

  addLocalStorage(notes.value);
  router.push("/homePosts");
  
  newWriter.value = "";
  newHeadline.value = "";
  newNote.value = "";
};

const addLocalStorage = (notesArr) => {
  localStorage.setItem("notes", JSON.stringify(notesArr));
};
</script>

二、homePosts.vue 存在的问题及修复

1. 未从localStorage读取数据

组件未定义notes变量,也未加载已存储的文章数据,导致v-for无数据源可遍历。

2. 未使用响应式变量

需用组合式API定义响应式notes,并在组件挂载时读取localStorage数据。

修改后的homePosts.vue代码:

<template>
  <div class="post-container">
    <h1>Blog Posts</h1>
    <div class="post-mini-container"> 
      <div class="post" v-for="note in notes" :key="note.id">
        <p class="writer"> {{ note.writer }}</p>
        <p class="headline"> {{ note.headline }}</p>
        <p class="blog-text" > {{ note.text }}</p>
      </div>
      <div v-if="notes.length === 0" class="empty-tip">暂无文章,快去发布第一篇吧!</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";

const notes = ref([]);

onMounted(() => {
  const savedNotes = localStorage.getItem("notes");
  if (savedNotes) {
    notes.value = JSON.parse(savedNotes);
  }
});
</script>

额外优化建议

  • 为输入框添加必填校验,避免存入空内容的文章
  • 补充图片上传逻辑,可将图片转为base64格式存入localStorage
  • 用时间戳+随机数生成文章ID,避免重复

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 00:01:09