Appearance
tryOnMounted
安全执行挂载回调 — 在组件生命周期内使用 onMounted,在组件外则立即执行。
函数签名
ts
function tryOnMounted(fn: Fn, sync?: boolean, target?: any): void基础用法
参数
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| fn | 需要执行的回调函数 | Fn | — |
| sync | 组件外是否同步执行(false 则放入 nextTick) | boolean | true |
| target | 生命周期绑定的目标实例 | any | — |
行为说明
- 在组件 setup 中调用:等同于
onMounted(fn),在组件挂载后执行 - 在组件外调用(如普通函数、模块顶层):
sync = true:立即执行fn()sync = false:在nextTick()中执行
代码示例
ts
import { ref } from 'vue'
import { tryOnMounted } from 'ljf-hooks'
const el = ref<HTMLElement>()
// 在 setup 中调用,等同于 onMounted
tryOnMounted(() => {
el.value.style.backgroundColor = 'blue'
})
// 在组件外调用,立即执行
tryOnMounted(() => {
console.log('立即执行')
})