vue依赖缓存_Vue SSR服务端渲染之数据缓存
當咱們在作vue的服務器端渲染時,可能會碰到各類各樣的坑,內存泄露就是其中的一種。固然,致使內存泄露的緣由有不少,不合理使用Axios也是其中一種,那下面我給你們介紹一下如何有效的避免請求中的內存泄露。vue
1. 安裝緩存依賴: lru-cache
npm install lru-cache --dev
2. api 配置文件
config-server.jsnode
var LRU = require('lru-cache')
let api
if (process.__API__) {
api = process.__API__
} else {
api = process.__API__ = {
api: 'http://localhost:8181/api/',
//配置緩存
cached: LRU({
max: 1000,
maxAge: 1000 * 60 * 15
}),
cachedItem: {}
}
}
module.exports = api
3. 封裝下 api
import axios from 'axios'
import qs from 'qs'
import md5 from 'md5'
import config from './config-server.js'
export default {
post(url, data) {
const key = md5(url + JSON.stringify(data))
if (config.cached && config.cached.has(key)) {
return Promise.resolve(config.cached.get(key))
}
return axios({
method: 'post',
url: config.api + url,
data: qs.stringify(data),
// 其余配置
}).then(res => {
if (config.cached && data.cache) config.cached.set(key, res)
return res
})
}
}
ajax 庫咱們用axios, 由于axios在 nodejs 和 瀏覽器均可以使用,而且將 node 端和瀏覽器端分開封裝ios
import config from './config-server.js'
const key = md5(url + JSON.stringify(data))
經過 url 和參數, 生成一個惟一的 keyajax
if (config.cached && config.cached.has(key)) {
return Promise.resolve(config.cached.get(key))
}
if (config.cached && data.cache) config.cached.set(key, res)
判斷下是否是開啟了緩存, 而且接口指定緩存的話, 將 api 返回的數據, 寫入緩存npm
注意:這個 api 會處理全部的請求, 可是不少請求實際上是不須要緩存的, 因此須要緩存能夠在傳過來的 data 里, 添加個 cache: true, 如:axios
api.post('/api/test', {a: 1, b:2, cache: true})
不須要緩存的直接按正常傳值便可api
總結
以上是生活随笔為你收集整理的vue依赖缓存_Vue SSR服务端渲染之数据缓存的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中给函数赋读权限_教你如何使用MCGS昆
- 下一篇: html5倒计时秒杀怎么做,vue 设