useLive()
异步渲染由远端触发的数据变更。
将 useSuspense() + useSubscription() 合二为一的 composable。
useLive() 会响应数据变更,仅在必要时重新渲染。
用法
Ticker
AssetPrice.vue
<script setup lang="ts"> import { computed } from 'vue'; import { useLive } from '@data-client/vue'; import { getTicker } from './Ticker'; import NumberFlow from '@number-flow/vue'; const props = defineProps<{ productId: string }>(); // highlight-next-line const ticker = await useLive(getTicker, computed(() => ({ productId: props.productId, }))); </script> <template> <div style="text-align: center"> {{ productId }} <NumberFlow :value="ticker.price" :format="{ style: 'currency', currency: 'USD' }" /> </div> </template>
与 useSuspense() 一样,useLive() 返回一个 Promise,因此需要在
<script setup> 中配合 await 使用,并且需要一个 Suspense 祖先组件。组件卸载时,订阅会自动移除。
行为
条件依赖
将 null 作为任意 Data Client hook 的第二个参数,表示“什么都不做”。
// todo could be undefined if id is undefined
const todo = useLive(
TodoResource.get,
computed(() => (id.value ? { id: id.value } : null)),
);
类型
function useLive(
endpoint: ReadEndpoint,
...args: MaybeRefsOrGetters<Parameters<typeof endpoint>> | [null]
): Promise<DeepReadonly<ComputedRef<Denormalize<typeof endpoint.schema>>>>;
参数可以是普通值、refs(包括 computed),或者像 () => ({ id: props.id }) 这样的 getter
函数。像 { id: props.id } 这样的普通对象只会被读取一次,不会跟随 prop 或路由的变化,因此当参数可能变化时,请使用 getter 或 computed。
参数变化时,结果会随之更新(订阅也会重新建立)。在加载新参数对应的数据期间,结果会保留之前的数据,而不会变为 undefined。如果这次获取失败,读取结果时会抛出该错误(取决于其错误策略),从而被
onErrorCaptured() 捕获。
示例
比特币价格(轮询)
当使用了 useLive 的组件被渲染时,getTicker 会每隔 pollFrequency
毫秒获取一次。