Skip to content

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.

提示

结果不会自动清除。如果你不再需要结果或使用自己的缓存机制以避免内存泄漏,请调用 clear()

¥The results are not cleared automatically. Call clear() in case you no longer need the results or use own caching mechanism to avoid memory leaks.

用法

¥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 cache
js
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

computedasyncComputed 结合以实现反应式性:

¥Combine with computed or asyncComputed to achieve reactivity:

ts
const user1 = asyncComputed(() => 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

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 {}

类型声明

显示类型声明
typescript
type CacheKey = any
/**
 * Custom memoize cache handler
 */
export interface UseMemoizeCache<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
}
/**
 * Memoized function
 */
export interface UseMemoizeReturn<Result, Args extends unknown[]> {
  /**
   * Get result from cache or call memoized function
   */
  (...args: Args): Result
  /**
   * Call memoized function and update cache
   */
  load: (...args: Args) => Result
  /**
   * Delete cache of given arguments
   */
  delete: (...args: Args) => void
  /**
   * Clear cache
   */
  clear: () => void
  /**
   * Generate cache key for given arguments
   */
  generateKey: (...args: Args) => CacheKey
  /**
   * Cache container
   */
  cache: UseMemoizeCache<CacheKey, Result>
}
export interface UseMemoizeOptions<Result, Args extends unknown[]> {
  getKey?: (...args: Args) => string | number
  cache?: UseMemoizeCache<CacheKey, Result>
}
/**
 * Reactive function result cache based on arguments
 */
export declare function useMemoize<Result, Args extends unknown[]>(
  resolver: (...args: Args) => Result,
  options?: UseMemoizeOptions<Result, Args>,
): UseMemoizeReturn<Result, Args>

源代码

源代码文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号