useForesight
useForesight registers a single element and gives you back the element's reactive prediction state as refs, plus an elementRef function to bind to the element. Use it over the v-foresight directive when you want to read state like isPredicted in your template.
<script setup lang="ts">
import { useForesight } from "@foresightjs/vue"
const { elementRef, isPredicted } = useForesight({
callback: () => console.log("user is likely to click this"),
name: "about-link",
hitSlop: 10,
})
</script>
<template>
<a :ref="elementRef" href="/about" :class="{ predicted: isPredicted }">About</a>
</template>
Bind elementRef with :ref="elementRef" and the composable handles the rest: it registers the element when it mounts, unregisters it when the component is disposed, and re-registers if the element swaps. elementRef works on plain elements and on component instances (it pulls out the underlying element for you).
Options
The options are the registration options, minus the element (elementRef handles that). callback is the only required field.
To make options reactive, pass a ref, reactive object, or getter. The composable updates the registration in place when options change. Each options object describes the full configuration, so omitted fields reset to their defaults:
<script setup lang="ts">
import { ref } from "vue"
import { useForesight } from "@foresightjs/vue"
const enabled = ref(true)
const { elementRef } = useForesight(() => ({
callback: () => prefetch("/about"),
name: "about-link",
enabled: enabled.value,
}))
</script>
Reactive state
Every state field comes back as a reactive ref, so reading it in your template re-renders when it changes. The ones you'll reach for most:
isPredicted→ the callback has fired for this elementisActive→ eligible to fire (not disabled, not on a limited connection, not parked)isParked→ detached from the DOM and parked; resumes when it reconnectsisCallbackRunning→ your (awaited) callback is mid-flighthitCount,status,error→ how the last run went
<script setup lang="ts">
const { elementRef, isPredicted, isCallbackRunning } = useForesight({
callback: async () => {
await fetch("/api/about")
},
name: "about",
})
</script>
<template>
<a :ref="elementRef" href="/about" :class="{ predicted: isPredicted }">
About <span v-if="isCallbackRunning">…</span>
</a>
</template>