useRuntimeHook

在 Nuxt 应用中注册运行时钩子,并确保在作用域销毁时正确处理该钩子。
此可组合项在 Nuxt v3.14+ 版本中可用。
signature
function useRuntimeHook<THookName extends keyof RuntimeNuxtHooks>(
  name: THookName,
  fn: RuntimeNuxtHooks[THookName] extends HookCallback ? RuntimeNuxtHooks[THookName] : never
): void

用法

¥Usage

参数

¥Parameters

  • name:要注册的运行时钩子的名称。你可以查看 运行时 Nuxt 钩子 的完整列表。
  • fn:触发钩子时执行的回调函数。函数签名根据钩子名称而变化。

返回值

¥Returns

可组合项不返回值,但当组件的作用域被销毁时,它会自动注销钩子。

¥The composable doesn't return a value, but it automatically unregisters the hook when the component's scope is destroyed.

示例

¥Example

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>