跳到主要内容

useCache()

无需 fetch 即可渲染数据。

访问任意 Endpoint 的响应。在它被获取、设置或能从 store 中已有的 entity 推断出来之前,以及失效之后,都返回 undefined(参见行为)。这意味着“尚未加载”,而不是“服务器上不存在”,因此请把它用于由其他代码加载的数据,例如登录流程获取的当前用户。

useCache() 会响应数据变更,仅在必要时重新渲染。

用法​

<script setup lang="ts">
  import { useCache } from '@data-client/vue';
  import { UserResource } from './UserResource';
  import Unauthed from './Unauthed.vue';
  import Authorized from './Authorized.vue';

  // currentUser as ComputedRef<User | undefined>
  const currentUser = useCache(UserResource.current);
</script>

<template>
  <!-- currentUser is unwrapped in the template -->
  <Authorized v-if="currentUser" :user="currentUser" />
  <!-- user is not logged in -->
  <Unauthed v-else />
</template>

有关类型处理的更多信息,请参阅真值收窄

行为​

useCache() 返回一个 ComputedRef。下表描述的是它的 .value。

过期状态返回值条件
无效undefined不在 store 中、删除、失效、invalidIfStale
过时反规范化数据(首次渲染、参数变化)& 过期时间 < 当前时间
有效反规范化数据fetch 完成
undefined第二个参数传入 null
条件依赖

将 null 作为任意 Data Client hook 的第二个参数,表示“什么都不做”。

// todo could be undefined if id is undefined
const todo = useCache(
TodoResource.get,
computed(() => (id.value ? { id: id.value } : null)),
);

类型​

function useCache(
endpoint: ReadEndpoint,
...args: MaybeRefsOrGetters<Parameters<typeof endpoint.key>> | [null]
): ComputedRef<DenormalizeNullable<typeof endpoint.schema>>;

参数可以是普通值、refs(包括 computed),或者像 () => ({ id: props.id }) 这样的 getter 函数。像 { id: props.id } 这样的普通对象只会被读取一次,不会跟随 prop 或路由的变化,因此当参数可能变化时,请使用 getter 或 computed。

当参数变化时,结果会随之更新。