[摘要]本篇文章给大家带来的内容是关于vue服务端渲染页面缓存和组件缓存的介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。vue缓存分为页面缓存、组建缓存、接口缓存,这里我主要说...
本篇文章给大家带来的内容是关于vue服务端渲染页面缓存和组件缓存的介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
vue缓存分为页面缓存、组建缓存、接口缓存,这里我主要说到了页面缓存和组建缓存
页面缓存:
在server.js中设置
const LRU = require('lru-cache')
const microCache = LRU({
max: 100, // 最大缓存的数目
maxAge: 1000 // 重要提示:条目在 1 秒后过期。
})
const isCacheable = req => {
//判断是否需要页面缓存
if (req.url && req.url === '/') {
return req.url
} else {
return false
}
}
app.get('*', (req, res) => {
const cacheable = isCacheable(req)
if (cacheable) {
const hit = microCache.get(req.url)
if (hit) {
return res.end(hit)
}
}
const errorHandler = err => {
if (err && err.code === 404) {
// 未找到页面
res.status(404).sendfile('public/404.html');
} else {
// 页面渲染错误
res.status(500).end('500 - Internal Server Error')
console.error(`error during render : ${req.url}`)
console.error(err)
}
}
const context = {
title: 'vue',
keywords: 'vue-ssr服务端脚手架',
description: 'vue-ssr-template, vue-server-renderer',
version: v,
url: req.url,
cookies: req.cookies
}
renderer.renderToString(context, (err, html) => {
if (err) {
return errorHandler(err)
}
res.end(html)
microCache.set(req.url, html) // 设置当前缓存页面的内容
})
})