- 在父组件监听子组件的生命周期
// 父组件监听子组件mounted
<el-child @hook:mounted="handleChildMounted"></el-child>
<script>
handleChildMounted () {
// do something
}
<script>
this.$on/$once('hook:生命周期',callback)
在实际运用中,我们常在mounted生命周期中,使用hook监听beforeDestroy,在beforeDestroy内部处理代码的清理和销毁工作。这样做的好处是代码的处理和清除是在一起的,从代码组织上来看,更友好。
mounted () {
bus.$on('pageSize', this.handlePageSize);
this.timer = setInterval(() => {
// dosomething
}, 1000)
this.$once('hook:beforeDestroy', () => {
// 销毁定时器
clearInterval(this.timer);
// 清除事件监听
bus.$off('pageSize', this.handlePageSize);
})
pageSize ( ) {
// do something
}
}