useRuntimeHook
在 Nuxt 应用中注册运行时钩子 (Runtime Hook),并确保在作用域销毁时自动将其注销。
此组合式函数 (Composable) 可用于 Nuxt v3.14 及以上版本。
签名
function useRuntimeHook<THookName extends keyof RuntimeNuxtHooks> (
name: THookName,
fn: RuntimeNuxtHooks[THookName] extends HookCallback ? RuntimeNuxtHooks[THookName] : never,
): void
使用
参数
name:要注册的运行时钩子名称。你可以在此处查看完整的 Nuxt 运行时钩子列表。fn:钩子触发时执行的回调函数。函数签名取决于钩子名称。
返回值
该组合式函数不返回任何值,但它会在组件作用域销毁时自动注销该钩子。
示例
pages/index.vue
<script setup lang="ts">
// Register a hook that runs every time a link is prefetched, but which will be
// automatically cleaned up (and not called again) when the component is unmounted
useRuntimeHook('link:prefetch', (link) => {
console.log('Prefetching', link)
})
</script>