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

Vue.js读取LocalStorage数据并渲染指定表格的实现疑问

调整方案

问题根源

你当前的代码直接将localStorage对象绑定到store上,读取到的是未解析的JSON字符串,且表头与目标结构不匹配,所以无法拆分字段展示。需要先把每个存储的JSON字符串解析为JavaScript对象,再重新组织数据结构,最后修改模板渲染对应的字段。

修改后的完整代码

<template>
    <div class="localstorage"> 
      <h1>Read From LocalStorage</h1>
      <table>
        <thead>
          <tr>
            <th>Key</th>
            <th>Name</th>
            <th>Age</th>
            <th>Mail</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in parsedStore" :key="item.key">
            <td>{{ item.key }}</td>
            <td>{{ item.Name || '-' }}</td>
            <td>{{ item.Age || '-' }}</td>
            <td>{{ item.Mail || '-' }}</td>
          </tr>
        </tbody>
      </table>
    </div>
</template>

<script>
// 原代码中axios未使用,可删除
export default {
  data() {
    return {
      // 不再直接绑定localStorage,改用计算属性处理数据
    }
  },
  computed: {
    parsedStore() {
      const processedItems = [];
      // 遍历localStorage所有键值对
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        const rawValue = localStorage.getItem(key);
        try {
          // 将存储的JSON字符串解析为可访问的对象
          const parsedValue = JSON.parse(rawValue);
          // 组合key与解析后的字段,形成统一结构
          processedItems.push({ key, ...parsedValue });
        } catch (err) {
          // 处理JSON解析失败的情况,避免页面报错
          processedItems.push({ key, Name: '解析失败', Age: '-', Mail: '-' });
        }
      }
      return processedItems;
    }
  },
}
</script>

关键修改点

  • 数据解析:通过JSON.parse()把localStorage中存储的JSON字符串转为可直接访问的对象,避免展示原始字符串。
  • 数据重组:遍历localStorage所有键值对,将每个项的key和解析后的Name/Age/Mail字段组合成新对象,方便模板渲染。
  • 模板调整:修改表头为目标的Key、Name、Age、Mail,并在表格行中直接访问每个字段的值。
  • 容错处理:添加try-catch捕获JSON解析错误,避免因存储数据格式异常导致页面崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 19:10:31