【发布时间】:2020-05-19 15:45:59
【问题描述】:
我正在使用 vue + nuxt.js 应用程序,我想知道是否可以为所有客户端缓存 axios webservice 调用。我必须获取一些货币参考数据,而每个客户都必须调用这些数据并没有多大意义。
有人可以给我一些提示甚至是一个例子吗?谢谢。
【问题讨论】:
标签: vue.js caching axios nuxt.js
我正在使用 vue + nuxt.js 应用程序,我想知道是否可以为所有客户端缓存 axios webservice 调用。我必须获取一些货币参考数据,而每个客户都必须调用这些数据并没有多大意义。
有人可以给我一些提示甚至是一个例子吗?谢谢。
【问题讨论】:
标签: vue.js caching axios nuxt.js
这是最新 Nuxt 2.11 的工作解决方案,使用本地定义的模块。
首先在nuxt.config.js中添加一个本地模块
modules: [
"@/modules/axCache",
...
]
然后
// modules/axCache.js
import LRU from "lru-cache"
export default function(_moduleOptions) {
const ONE_HOUR = 1000 * 60 * 60
const axCache = new LRU({ maxAge: ONE_HOUR })
this.nuxt.hook("vue-renderer:ssr:prepareContext", ssrContext => {
ssrContext.$axCache = axCache
})
}
和
// plugins/axios.js
import { cacheAdapterEnhancer } from "axios-extensions"
import LRU from "lru-cache"
const ONE_HOUR = 1000 * 60 * 60
export default function({ $axios, ssrContext }) {
const defaultCache = process.server
? ssrContext.$axCache
: new LRU({ maxAge: ONE_HOUR })
const defaults = $axios.defaults
// https://github.com/kuitos/axios-extensions
defaults.adapter = cacheAdapterEnhancer(defaults.adapter, {
enabledByDefault: false,
cacheFlag: "useCache",
defaultCache
})
}
请注意,这适用于服务器/客户端,并且可以配置为仅在一侧工作。
解决方案位于:https://github.com/nuxt-community/axios-module/issues/99
【讨论】:
这里是缓存整个页面的新解决方案
如果你需要的话,你甚至可以缓存一致的 api like menu
https://www.npmjs.com/package/nuxt-perfect-cache
npm i nuxt-perfect-cache
// nuxt.config.js
modules: [
[
'nuxt-perfect-cache',
{
disable: false,
appendHost: true,
ignoreConnectionErrors:false, //it's better to be true in production
prefix: 'r-',
url: 'redis://127.0.0.1:6379',
getCacheData(route, context) {
if (route !== '/') {
return false
}
return { key: 'my-home-page', expire: 60 * 60 }//1hour
}
}
]
]
然后为所有客户端在 redis 中缓存您的 api 响应:
asyncData(ctx) {
return ctx.$cacheFetch({ key: 'myApiKey', expire: 60 * 2 }, () => {
console.log('my callback called*******')
return ctx.$axios.$get('https://jsonplaceholder.typicode.com/todos/1')
})
}
【讨论】: