Lzh on GitHub

tryOnMounted 是一个实用函数,它安全地调用 onMounted() 钩子。如果代码在 Vue 组件的生命周期内执行,它会像 onMounted() 一样工作;否则,它会立即执行传入的函数。

用法

import { tryOnMounted } from '@vueuse/core'

tryOnMounted(() => {
  // 这段代码将在组件挂载后执行,如果不在组件生命周期内,则立即执行。
  console.log('组件已挂载或代码立即执行')
})

类型声明

/**
 * Call onMounted() if it's inside a component lifecycle, if not, just call the function
 *
 * @param fn
 * @param sync if set to false, it will run in the nextTick() of Vue
 * @param target
 */
export declare function tryOnMounted(fn: Fn, sync?: boolean, target?: any): void