主题
useMemoize
缓存依赖于参数的函数结果,并保持其响应性。它也可以用于异步函数,并会重复使用现有的 Promise,以避免同时获取相同的数据。
🌐 Cache results of functions depending on arguments and keep it reactive. It can also be used for asynchronous functions and will reuse existing promises to avoid fetching the same data at the same time.
TIP
结果不会自动清除。如果不再需要结果,请调用 clear(),或者使用自己的缓存机制以避免内存泄漏。
用法
🌐 Usage
ts
import { useMemoize } from '@vueuse/core'
const getUser = useMemoize(
async (userId: number): Promise<UserData> =>
axios.get(`users/${userId}`).then(({ data }) => data),
)
const user1 = await getUser(1) // Request users/1
const user2 = await getUser(2) // Request users/2
// ...
const user1 = await getUser(1) // Retrieve from cache
// ...
const user1 = await getUser.load(1) // Request users/1
// ...
getUser.delete(1) // Delete cache from user 1
getUser.clear() // Clear full cachejs
import { useMemoize } from '@vueuse/core'
const getUser = useMemoize(async (userId) =>
axios.get(`users/${userId}`).then(({ data }) => data),
)
const user1 = await getUser(1) // Request users/1
const user2 = await getUser(2) // Request users/2
// ...
const user1 = await getUser(1) // Retrieve from cache
// ...
const user1 = await getUser.load(1) // Request users/1
// ...
getUser.delete(1) // Delete cache from user 1
getUser.clear() // Clear full cache与 computed 或 computedAsync 结合以实现反应性:
🌐 Combine with computed or computedAsync to achieve reactivity:
ts
const user1 = computedAsync(() => getUser(1))
// ...
await getUser.load(1) // Will also update user1解析缓存键
🌐 Resolving cache key
缓存的关键是由传入函数的参数决定的,并且默认会使用 JSON.stringify 进行序列化。这将允许相同的对象获得相同的缓存键。如果你想自定义键,可以传入 getKey
🌐 The key for caching is determined by the arguments given to the function and will be serialized by default with JSON.stringify. This will allow equal objects to receive the same cache key. In case you want to customize the key you can pass getKey
性能考虑
将 JSON.stringify 用作默认键生成器对于大型或复杂对象可能会很慢。对于复杂参数,为了获得更好的性能,强烈建议提供一个自定义的 getKey 函数,该函数基于原始值或唯一标识符生成键。
基本示例
🌐 Basic Example
ts
const getUser = useMemoize(
async (userId: number, headers: AxiosRequestHeaders): Promise<UserData> =>
axios.get(`users/${userId}`, { headers }).then(({ data }) => data),
{
// Use only userId to get/set cache and ignore headers
getKey: (userId, headers) => userId,
},
)js
const getUser = useMemoize(
async (userId, headers) =>
axios.get(`users/${userId}`, { headers }).then(({ data }) => data),
{
// Use only userId to get/set cache and ignore headers
getKey: (userId, headers) => userId,
},
)自定义缓存机制
🌐 Customize cache mechanism
默认情况下,结果会缓存在 Map 中。你可以通过传递以下结构的 cache 作为选项来实现自己的机制:
🌐 By default, the results are cached within a Map. You can implement your own mechanism by passing cache as options with following structure:
ts
export interface MemoizeCache<Key, Value> {
/**
* Get value for key
*/
get: (key: Key) => Value | undefined
/**
* Set value for key
*/
set: (key: Key, value: Value) => void
/**
* Return flag if key exists
*/
has: (key: Key) => boolean
/**
* Delete value for key
*/
delete: (key: Key) => void
/**
* Clear cache
*/
clear: () => void
}js
export {}