- data() {
- return {
- timer: null;
- };
- },
- created() {
- // 设置定时器,5s执行一次
- this.timer = setInterval(() => {
- console.log('setInterval');
- }, 5000);
- }
- beforeDestroy () {
- //清除定时器
- clearInterval(this.timer);
- this.timer = null;
- }
- created() {
- // 设置定时器,5s执行一次
- let timer = setInterval(() => {
- console.log('setInterval');
- }, 5000);
-
- // 离开当前页面时销毁定时器
- this.$once('hook:beforeDestroy', () => {
- clearInterval(timer);
- timer = null;
- })
- }
该方法与在生命周期钩子beforeDestroy中清除定时器的操作原理一样,但更有优势
1.无需在vue实例上定义定时器,减少不必要的内存浪费
2.设置和清除定时器的代码放在一块,可读性维护性更好
1、原因
<router-view>外层包裹了一层
< keep-alive > 有缓存的作用,可以使被包裹的组件状态维持不变,当路由被 keep-alive 缓存时不走 beforeDestroy 生命周期。被包含在 < keep-alive > 中创建的组件,会多出两个生命周期钩子: activated 与 deactivated。
activated
在组件被激活时调用,在组件第一次渲染时也会被调用,之后每次keep-alive激活时被调用。
deactivated
在组件失活时调用。
2、解决方案
借助 activated 和 deactivated 钩子来设置和清除定时器
(1)生命周期钩子
- created() {
- // 页面激活时设置定时器
- this.$on("hook:activated", () => {
- let timer = setInterval(()=>{
- console.log("setInterval");
- },1000)
- })
-
- // 页面失活时清除定时器
- this.$on("hook:deactivated", ()=>{
- clearInterval(timer);
- timer = null;
- })
- }
(2)hook
- data() {
- return {
- timer: null // 定时器
- }
- },
- activated() {
- // 页面激活时开启定时器
- this.timer = setInterval(() => {
- console.log('setInterval');
- }, 5000)
- },
- deactivated() {
- // 页面关闭(路由跳转)时清除定时器
- clearInterval(this.timer)
- this.timer = null
- },