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

求助:如何用Nuxt Pinia通过fetch获取本地JSON文件?当前实现失效

用fetch()获取本地JSON文件并实时更新数据

当然可以用fetch()获取本地JSON文件,你的代码无法运行主要是路径错误和缺少错误处理导致的,下面是修正方案:

1. 调整JSON文件存放位置

把data.json放到项目根目录的public文件夹下(没有的话直接新建),Nuxt会把public目录下的文件作为静态资源部署到服务器根目录,这样就能通过绝对路径访问。

2. 修正Pinia Store的代码

改用async/await优化代码可读性,同时添加错误处理和路径修正:

export const useCharactersStore = defineStore("characters", {
  state: () => ({
    characters: [],
  }),
  getters: {
    getCharacters: (state) => state.characters,
  },
  actions: {
    async fetchCharacters() {
      try {
        // 用绝对路径请求public目录下的data.json
        const response = await fetch("/data.json");
        // 检查请求是否成功
        if (!response.ok) {
          throw new Error(`请求失败,状态码:${response.status}`);
        }
        const data = await response.json();
        this.characters = data.characters;
      } catch (err) {
        console.error("加载字符数据出错:", err);
      }
    },
  },
});

3. 原代码的问题说明

  • 路径错误:你用的../data.json是相对于源码文件的路径,但fetch的路径是相对于浏览器地址栏的URL,不是源码位置,所以会找不到文件。
  • 缺少错误处理:没有处理请求失败、JSON解析失败等情况,出错后无法排查问题。
  • then链可读性差:async/await比嵌套then更易维护。

4. 额外优化(可选)

如果需要在开发环境下修改data.json后自动更新数据,可以在app.vue里添加定时刷新逻辑:

import { useCharactersStore } from "~/stores/characters";

const store = useCharactersStore();

onMounted(() => {
  store.fetchCharacters();
  // 开发环境下每隔5秒刷新一次数据
  if (process.env.NODE_ENV === "development") {
    setInterval(() => {
      store.fetchCharacters();
    }, 5000);
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:40:41