文章目录
- 参考
- 知识点
- 定时器清除案例
- mounted 和 beforeDestroy 生命周期函数配套使用
- mounted中处理所有(hook:beforeDestroy)
- 外部监听生命周期函数
参考
- 实战技巧,Vue原来还可以这样写
- Vue 程序化的事件侦听器
知识点
组件的所有生命周期钩子都可以通过@hook:钩子函数名 来监听触发
定时器清除案例
mounted 和 beforeDestroy 生命周期函数配套使用
export default {data: function () {return {timer: null}},mounted () {this.timer = setInterval(() => {console.log('time' + new Date().getTime())}, 1000)},beforeDestroy () {if (this.timer) {console.log('销毁定时器')clearInterval(this.timer)}}
}
mounted中处理所有(hook:beforeDestroy)
export default {name: '',mounted () {let timer = setInterval(() => {console.log('time' + new Date().getTime())}, 1000)this.$once('hook:beforeDestroy', function () {clearInterval(timer)console.log('第一个 hook' + timer)})this.$once('hook:beforeDestroy', function () {console.log('第二个 hook' + timer)})},
}
外部监听生命周期函数
应用场景说明
- 使用的第三方组件,对于开发者来说内部就是一个沙盒,不了解内部的逻辑,并且不能修改内部代码
- 希望监听类似
change事件
,或者是在组件加载完之后执行某个业务逻辑
案例说明
<template><!--通过&#64;hook:updated监听组件的updated生命钩子函数--><!--组件的所有生命周期钩子都可以通过&#64;hook:钩子函数名 来监听触发--><custom-select &#64;hook:updated&#61;"myUpdated" />
</template>
<script>
import CustomSelect from &#39;../components/custom-select&#39;
export default {components: {CustomSelect},methods: {myUpdated() {console.log(&#39;custom-select组件的updated钩子函数被触发&#39;)}}
}
</script>