Composable
The useForesight composable provides a Vue-native way to integrate ForesightJS into your Vue components. Unlike the v-foresight directive, the composable gives you direct access to registerResults and the element's templateRef, but requires more setup code.
Basic useForesight
Copy belows code in a /composables/useForesight.ts file
import { ref, onMounted, useTemplateRef, readonly, type ComponentPublicInstance } from "vue"
import {
ForesightManager,
type ForesightRegisterOptionsWithoutElement,
type ForesightRegisterResult,
} from "js.foresight"
type UseForesightOptions = ForesightRegisterOptionsWithoutElement & {
templateRefKey: string
}
export function useForesight<T extends HTMLElement | ComponentPublicInstance>(
options: UseForesightOptions
) {
const templateRef = useTemplateRef<T>(options.templateRefKey)
const registerResults = ref<ForesightRegisterResult | null>(null)
onMounted(() => {
if (!templateRef.value) {
return
}
// Extract the underlying HTMLElement if the templateRef is a Vue component
const element =
templateRef.value instanceof HTMLElement ? templateRef.value : templateRef.value.$el
registerResults.value = ForesightManager.instance.register({
element,
...options,
})
})
return {
templateRef,
registerResults: readonly(registerResults),
}
}
Return Values
The composable returns an object containing:
templateRef- Template ref to attach to your target element usingref="yourRefKey"registerResults- Registration details likeisRegistered
Basic Usage
This is the most basic way to use the composable and is basically the same as using the v-foresight directive.
<script setup lang="ts">
import { useForesight } from "./composables/useForesight"
useForesight({
templateRefKey: "myButton",
callback: () => {
console.log("Prefetching data...")
},
hitSlop: 10,
name: "my-button",
})
</script>
<template>
<button ref="myButton">Hover to prefetch</button>
</template>
Getting the templateRef
The composable also returns the templateRef, giving you direct access to the underlying element or component instance.
<script setup lang="ts">
import { useForesight } from "./composables/useForesight"
import MyCustomComponent from "./MyCustomComponent.vue"
const { templateRef } = useForesight<InstanceType<typeof MyCustomComponent>>({
templateRefKey: "myComponent", // Must match the ref attribute on your element
callback: () => {
console.log("Prefetching...")
},
})
</script>
<template>
<MyCustomComponent ref="myComponent" />
</template>
When you want to access the templateRef of a Vue component, you must pass InstanceType<typeof YourComponent> as the generic type parameter to get the correct component instance type. This is only necessary when destructuring templateRef from the return value.