useCache()
无需 fetch 即可渲染数据。
访问任意 Endpoint 的响应。如果响应不存在,则返回
undefined。这可以用来检查某个 Endpoint's 的响应是否存在,例如用于身份验证。
useCache() 会响应数据变更,仅在必要时重新渲染。
用法
UserResource
Unauthed.vue
Authorized.vue
AuthorizedPage.vue
<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。
当参数变化时,结果会随之更新。