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

Nuxt.js中如何用Axios缓存指定JSON请求数据?

Nuxt 2.14.12 + @nuxtjs/axios@5.12.5 实现GET请求缓存方案

你的场景是:项目中某个GET请求(获取JSON数据)被多处调用,且数据不常更新,需要实现缓存,之前考虑过axios-cache-plugin,下面提供几个简单可行的方案:

方案1:利用Nuxt内置页面缓存(适合页面级数据)

如果请求是在页面组件中发起,直接用Nuxt自带的asyncData/fetch结合缓存配置即可,无需额外依赖。

示例代码:

export default {
  async asyncData({ $axios }) {
    const response = await $axios.get(`${url}/data.json`)
    return { dataResponse: response.data.response }
  },
  // 配置缓存时长(单位:秒,示例为1小时)
  cache: {
    maxAge: 3600
  }
}

说明:Nuxt会自动缓存asyncData的返回结果,同一页面多次访问时会复用缓存数据,适合服务端渲染或静态生成的场景。

方案2:手动实现内存缓存(灵活可控,无依赖)

自己封装一个带缓存的请求方法,完全可控,适合任意组件调用。

  1. 在项目plugins目录下创建axios-cache.js:
export default ({ $axios }, inject) => {
  // 用Map存储缓存数据
  const cacheStore = new Map()

  // 封装带缓存的GET方法,默认缓存1小时
  const cachedGet = async (requestUrl, cacheDuration = 3600000) => {
    const currentTime = Date.now()
    // 检查缓存是否存在且未过期
    if (cacheStore.has(requestUrl)) {
      const { timestamp, data } = cacheStore.get(requestUrl)
      if (currentTime - timestamp < cacheDuration) {
        return data
      }
      // 缓存过期则移除
      cacheStore.delete(requestUrl)
    }
    // 发起新请求并缓存结果
    const response = await $axios.get(requestUrl)
    const targetData = response.data.response
    cacheStore.set(requestUrl, { timestamp: currentTime, data: targetData })
    return targetData
  }

  // 挂载到Vue实例,全局可用
  inject('cachedAxiosGet', cachedGet)
}
  1. 在nuxt.config.js中注册插件:
export default {
  plugins: [
    '~/plugins/axios-cache.js'
  ]
}
  1. 在组件中使用:
this.$cachedAxiosGet(`${url}/data.json`)
  .then(data => {
    this.dataResponse = data
  })

说明:可以根据需求自定义缓存时长、缓存清理规则,完全不用依赖第三方插件,代码轻量。

方案3:使用axios-cache-plugin(现成插件,快速接入)

你之前考虑的axios-cache-plugin完全适用,配置简单,无需大幅修改原有请求代码。

  1. 安装插件:
npm install axios-cache-plugin --save
  1. 在plugins目录下创建axios-cache-plugin.js:
import axiosCachePlugin from 'axios-cache-plugin'

export default ({ $axios }, inject) => {
  // 初始化缓存插件
  axiosCachePlugin($axios, {
    maxCacheSize: 100, // 最大缓存条目数
    cacheExpireTime: 3600000 // 缓存时长(毫秒,示例为1小时)
  })
  // 全局开启GET请求缓存,也可以给单个请求单独配置
  $axios.defaults.cache = true
}
  1. 在nuxt.config.js中注册插件后,原有请求代码无需修改,会自动触发缓存:
this.$axios.get(`${ url }/data.json`)
  .then((response) => {
    this.dataResponse = response.data.response
  })

说明:插件已经封装好缓存逻辑,适合不想自己写代码的场景,能满足基本缓存需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 08:30:21