vue2 可中轻松监听生命钩子:
mounted() {
const onResize = () => {
console.log('onResize')
}
window.addEventListener('resize', onResize)
// hook:liefHook
this.$once('hook:beforeDestroy', () => {
window.removeEventListener('resize', onResize)
})
}
vue3 我也希望使用这种语法,vue3 不再支持 this.$once
,根据 vue3 中event bus
import { event } from '@utils'
onMounted(() => {
console.log('vue3 mounted')
function onResize() {
console.log('onResize')
}
window.addEventListener('resize', onResize)
event.once('vnode-before-unmount', () => {
console.log('vnode-before-unmount')
removeEventListener('resize', onResize)
})
})
event 的定义:
import emitter from 'tiny-emitter/instance'
export const event = {
emit: (...args) => emitter.emit(...args),
on: (...args) => emitter.on(...args),
off: (...args) => emitter.off(...args),
once: (...args) => emitter.once(...args),
}
组件销毁时,不会执行event.once
的回调。
在组件上监听生命周期:
<DemoV2 @vnode-mounted="mounted" @vnode-before-unmount="beforeUnmount" />
正常的。
请问为何event.once
不生效?
你可能没明白
组合式api
/hooks
的真正用法这种情况也不需要
once