組件緩存
雖然 Vue 的 SSR 非成ッ唬快,但由于創(chuàng)建組件實(shí)例和 Virtual DOM 節(jié)點(diǎn)的成本冠摄,它無法與純粹基于字符串的模板的性能相匹配桐经。在 SSR 性能至關(guān)重要的情況下,合理地利用緩存策略可以大大縮短響應(yīng)時(shí)間并減少服務(wù)器負(fù)載主到。
使用
- 使用 yarn 或 npm 將
@nuxtjs/component-cache
依賴項(xiàng)添加到項(xiàng)目中 - 將
@nuxtjs/component-cache
添加到nuxt.config.js
的modules部分
{
modules: [
// 簡單的用法
'@nuxtjs/component-cache',
// 配置選項(xiàng)
[
'@nuxtjs/component-cache',
{
max: 10000,
maxAge: 1000 * 60 * 60
}
]
]
}
注意:
- 可緩存組件必須定義唯一 name 選項(xiàng)茶行。
- 不應(yīng)該緩存組件的情況
- 可能擁有依賴global數(shù)據(jù)的子組件。
- 具有在渲染context中產(chǎn)生副作用的子組件登钥。
要緩存的組件
export default {
name: 'item', // required
props: ['item'],
serverCacheKey: props => props.item.id,
render (h) {
return h('div', this.item.id)
}
}
頁面緩存
安裝 lru-cache
用到 nuxt.config.js
中的 serverMiddleware
新建服務(wù)器端中間件處理緩存文件 pageCache.js
const LRU = require('lru-cache');
export const cachePage = new LRU({
max: 100, // 緩存隊(duì)列長度 最大緩存數(shù)量
maxAge: 1000 * 10, // 緩存時(shí)間 單位:毫秒
});
export default function(req, res, next) {
const url = req._parsedOriginalUrl;
const pathname = url.pathname;
// 本地開發(fā)環(huán)境不做頁面緩存(也可開啟開發(fā)環(huán)境進(jìn)行調(diào)試)
if (process.env.NODE_ENV !== 'development') {
// 只有首頁才進(jìn)行緩存
if (['/'].indexOf(pathname) > -1) {
const existsHtml = cachePage.get('indexPage');
if (existsHtml) {
// 如果沒有Content-Type:text/html 的 header畔师,gtmetrix網(wǎng)站無法做測評
res.setHeader('Content-Type', ' text/html; charset=utf-8');
return res.end(existsHtml.html, 'utf-8');
} else {
res.original_end = res.end;
res.end = function(data) {
if (res.statusCode === 200) {
// 設(shè)置緩存
cachePage.set('indexPage', {
html: data,
});
}
res.original_end(data, 'utf-8');
};
}
}
}
next();
}
在nuxt.config.js中配置serverMiddleware,引入
/*
** 服務(wù)器端中間件--針對首頁做緩存
*/
serverMiddleware: [
{
path: '/',
handler: '~/utils/server-middleware/pageCache.js',
},
]
清理緩存
如果需要清理緩存牧牢,請?jiān)?pageCahe.js 添加:
// 清理緩存
if (pathname === '/cleancache') {
cachePage.reset();
res.statusCode = 200;
}
并同樣添加到 nuxt.config.js中
{
path: '/cleancache',
handler: '~/utils/server-middleware/pageCache.js',
},