Skip to content
On this page

vue3 如何监听生命周期钩子事件

有时候需要父组件需要知道子组件的生命周期钩子事件,比如子组件的mounted钩子事件,父组件需要在子组件mounted钩子事件执行完毕后,再执行一些操作。

比如 animate.css 和 element-plus 一起使用,animate 的样式权重太高,让 element-plus 分页有禁用样式。

animate.css和ele样式冲突

希望在分页组件挂载和更新后移除disabled属性。

vue3 提供了生命周期钩子事件。

这个需求可以这样写。

html
<el-pagination @vnode-mounted="removePaginationDisabled" @vnode-updated="removePaginationDisabled" />

jsx 写法

jsx
<ElPagination onVnodeMounted={removePaginationDisabled} onVnodeUpdated={removePaginationDisabled} />

在模板里还支持这样写

html
<el-pagination @vue:mounted="removePaginationDisabled" @vue:updated="removePaginationDisabled" />

这种写法在 jsx 中理论上这样写onVue:mounted也是支持的,但是测试了vue@3.2.47,不支持,这种不统一的存在,很让人迷惑。 使用第一种即可。

其他生命周期钩子事件

bash
onVnodeBeforeMount
onVnodeBeforeUpdate
onVnodeBeforeUnmount
onVnodeUnmounted

vue2 中也有类似的写法

bash
@hook:mounted
@hook:updated
@hook:beforeDestroy

参考

7 Vue3 tips you need to know

Vue 官方文档里没告诉你的神秘钩子——@hook

vue3 如何监听生命周期钩子?

Released under the MIT License.