[Vue warn]: onUnmounted is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.
当没有活动组件实例要关联时,调用onUnmounted。生命周期注入api只能在setup()执行期间使用。如果您正在使用async setup(),请确保在第一个await语句之前注册生命周期钩子。
报这个警告主要是因为生命周期函数onUnmounted等函数只能在setpu中使用,在延时函数中容易遇到,有可能超出这个范围就会出警告。写了一个小工具解决此问题
import { onUnmounted as _onUnmounted, onMounted as _onMounted } from 'vue'
type Hook = () => void
type LifeHook = (hook: Hook) => any
interface IHookItem {
hooks: LifeHook
queue: Hook[]
}
const hookMap: Record<string, IHookItem> = {
onUnmounted: {
hooks: _onUnmounted,
queue: [],
},
onMounted: {
hooks: _onMounted,
queue: [],
},
}
export function useLifeHook() {
const keys = Object.keys(hookMap)
return keys.reduce(
(p, key) => {
const hookItem = hookMap[key]
hookItem.hooks(() => {
hookItem.queue.forEach((v) => v())
})
return {
...p,
[key]: (hook: Hook) => hookItem.queue.push(hook),
}
},
{} as Record<string, LifeHook>,
)
}
使用方法示例
const { onUnmounted } = useLifeHook()
const enter = (el: Element, done: () => void) => {
el.addEventListener('transitionend', done)
useTimeout(
() => {
//延时要处理的逻辑
},
undefined,
onUnmounted,
)
}
import { onUnmounted as _onUnmounted } from 'vue'
//延时函数
export function useTimeout(fn: () => void, delay?: number, onUnmounted = _onUnmounted) {
const timer = setTimeout(fn, delay)
const clear = () => {
clearTimeout(timer)
}
onUnmounted(clear)
return clear
}