useSubscription()
让经常变化的数据保持最新。
默认的轮询订阅需要在 Endpoint 上设置 pollFrequency。如果没有设置,订阅时会记录一个错误,并且什么也不做。
提示
useLive() 在一次调用中组合了 useSubscription() 和 useSuspense()。
用法
Ticker
AssetPrice.vue
<script setup lang="ts"> import { useSuspense, useSubscription } from '@data-client/vue'; import NumberFlow from '@number-flow/vue'; import { getTicker } from './Ticker'; const props = defineProps<{ productId: string }>(); const ticker = await useSuspense(getTicker, () => ({ productId: props.productId, })); useSubscription(getTicker, () => ({ productId: props.productId })); </script> <template> <dl class="stats"> <div> <dt>{{ productId }}</dt> <dd> <NumberFlow :value="ticker.price" :format="{ style: 'currency', currency: 'USD' }" /> </dd> </div> </dl> </template>
行为
条件依赖
将 null 作为任意 Data Client hook 的第二个参数,表示“什么都不做”。没有路径参数或查询参数的 RestEndpoint 则用 {} 代替,比如 enabled ? {} : null。
// todo could be undefined if id is undefined
const todo = useSubscription(
TodoResource.get,
computed(() => (id.value ? { id: id.value } : null)),
);
订阅会在组件 setup 时创建,在组件卸载时移除。当以 ref 形式传入的参数发生变化时,之前的订阅会被移除,并为新参数创建新的订阅。
类型
function useSubscription(
endpoint: ReadEndpoint,
...args: MaybeRefsOrGetters<Parameters<typeof endpoint>> | [null]
): void;
参数可以是普通值、refs(包括 computed),或者像 () => ({ id: props.id }) 这样的 getter
函数。像 { id: props.id } 这样的普通对象只会被读取一次,不会跟随 prop 或路由的变化,因此当参数可能变化时,请使用 getter 或 computed。
示例
仅在元素可见时订阅
Ticker
AssetRow.vue
<script setup lang="ts"> import { computed, useTemplateRef } from 'vue'; import { useElementVisibility } from '@vueuse/core'; import { useSuspense, useSubscription } from '@data-client/vue'; import NumberFlow from '@number-flow/vue'; import { getTicker } from './Ticker'; const props = defineProps<{ productId: string }>(); const ticker = await useSuspense(getTicker, () => ({ productId: props.productId, })); const el = useTemplateRef('el'); const isVisible = useElementVisibility(el); // null args means don't subscribe useSubscription( getTicker, computed(() => isVisible.value ? { productId: props.productId } : null, ), ); </script> <template> <div ref="el" class="listItem"> <h4>{{ productId }}</h4> <NumberFlow class="value" :value="ticker.price" :format="{ style: 'currency', currency: 'USD' }" /> </div> </template>
第二个参数传入 null 会关闭该组件的订阅。只要还有其他组件订阅同一数据,更新就会继续。
VueUse 的 useElementVisibility() 使用了性能非常好的 IntersectionObserver。模板引用让你可以访问 DOM 元素。