详解Vue2 SSR 缓存 Api 数据
本文介绍了Vue2SSR缓存Api数据,分享给大家,具体如下:
1.安装缓存依赖:lru-cache
npminstalllru-cache--dev
2.api配置文件
config-server.js
varLRU=require('lru-cache')
letapi
if(process.__API__){
api=process.__API__
}else{
api=process.__API__={
api:'http://localhost:8080/api/',
cached:LRU({
max:1000,
maxAge:1000*60*15
}),
cachedItem:{}
}
}
module.exports=api
配置下lru-cache
3.封装下api
importaxiosfrom'axios'
importqsfrom'qs'
importmd5from'md5'
importconfigfrom'./config-server.js'
exportdefault{
post(url,data){
constkey=md5(url+JSON.stringify(data))
if(config.cached&&config.cached.has(key)){
returnPromise.resolve(config.cached.get(key))
}
returnaxios({
method:'post',
url:config.api+url,
data:qs.stringify(data),
//其他配置
}).then(res=>{
if(config.cached&&data.cache)config.cached.set(key,res)
returnres
})
}
}
ajax库我们用axios,因为axios在nodejs和浏览器都可以使用
并且将node端和浏览器端分开封装
importconfigfrom'./config-server.js'
constkey=md5(url+JSON.stringify(data))
通过url和参数,生成一个唯一的key
if(config.cached&&config.cached.has(key)){
returnPromise.resolve(config.cached.get(key))
}
if(config.cached&&data.cache)config.cached.set(key,res)
判断下是不是开启了缓存,并且接口指定缓存的话,将api返回的数据,写入缓存
注意:
这个api会处理所有的请求,但是很多请求其实是不需要缓存的,所以需要缓存可以在传过来的data里,添加个cache:true,如:
api.post('/api/test',{a:1,b:2,cache:true})
不需要缓存的直接按正常传值即可
当然这里标记是不是要缓存的方法有很多,不一定要用这一种
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。