useRenderCache() 组合式API在处理Vue渲染函数时特别有用(尽管不限于此)。当您通过迭代构建节点时,此组合式API可以帮助您内联代码,同时(出于性能原因)也能从缓存中受益。
在处理SSR时,在服务器端您不会希望缓存任何内容,因为渲染对每个客户端只会发生一次(并且您不希望内存占用无谓地增长)。因此,useRenderCache组合式API在服务器端实际上不会使用任何缓存,而是在每次调用时使用提供的默认值。
您可以直接缓存任何类型的值。一些例子:
- 您可以缓存一些监听器,这样Vue就不需要在每次重新渲染时移除并重新附加它们。
- 您可以缓存一些Vue渲染的节点,尽管在这种情况下您必须小心,因为它们的内容不应依赖于任何"响应式"内容(refs、computed等)。
语法
import { useRenderCache } from 'quasar'
setup () {
const {
getCache,
setCache,
hasCache,
clearCache
} = useRenderCache()
// ...
}content_paste
function useRenderCache(): {
getCache: <T = any>(key: string, defaultValue?: T | (() => T)) => T;
setCache: <T = any>(key: string, value: T) => void;
hasCache: (key: string) => boolean;
clearCache: (key?: string) => void;
};content_paste
示例
下一个示例缓存了一些监听器,以避免Vue在每个渲染周期中移除并重新附加它们:
import { h } from "vue";
import { useRenderCache } from "quasar";
export default {
setup() {
const { getCache } = useRenderCache();
function getNode(i) {
return h("div", {
onClick: getCache(`click#${i}`, () => {
console.log(`点击了节点 ${i}`);
}),
});
}
function getContent() {
const acc = [];
for (let i = 0; i < 10; i++) {
acc.push(getNode(i));
}
return acc;
}
return () => {
h("div", getContent);
};
},
};content_paste
以下示例缓存了一些值,并且仅当缓存中尚未设置此类键时才调用第二个参数(它是一个函数)来生成默认值。这样,即使缓存已经设置,我们也避免了不必要地运行该函数:
const { getCache } = useRenderCache();
getCache("my-key", () => {
// 一些计算,仅在缓存中
// 没有设置"my-key"时运行
return { some: "object" };
});content_paste
需要避免的陷阱
不要直接在Vue h() 函数的第二个参数上缓存。这会干扰Vue的DOM差异算法。
// 不要这样缓存:
h(
'div',
getCache(`node#${ i }`, () => {
return {
onClick () => { console.log(`点击了节点 ${ i }`) }
}
})
)
// ..而是这样做:
h(
'div',
{ // 在每次渲染时需要创建新的对象,
// 即使内容是缓存的
...getCache(`node#${ i }`, () => {
return {
onClick () => { console.log(`点击了节点 ${ i }`) }
}
})
}
)content_paste