Skip to main content

有依赖的查询 Dependent Queries

依赖查询(或串行查询)取决于先前的查询结果。要实现这一点,只需使用enabled选项就可以告诉查询何时可以运行:

// Get the user
const { data: user } = useQuery({
queryKey: ['user', email],
queryFn: () => getUserByEmail(email.value),
})

const userId = computed(() => user.value?.id)
const enabled = computed(() => !!user.value?.id)

// Then get the user's projects
const { isIdle, data: projects } = useQuery({
queryKey: ['projects', userId],
queryFn: () => getProjectsByUser(userId.value),
enabled, // 直到 `enabled == true`,query才会执行
})

projects的查询开始状态如下:

status: "loading";
fetchStatus: "idle";

一旦userId可用,projects的查询将被“启用”(enabled),然后状态转换为:

status: "loading";
fetchStatus: "fetching";

查询完成时,状态变成:

status: "success";
fetchStatus: "idle";