记录vue中component切换组件时销毁定时器问题
问题描述:有A、B两个子组件,通过component进行切换,子组件中有定时器,当切换组件时需要把定时器给注销掉。1、通过VUE组件生命周期进行删除定时器2、使用this.$once来监听定时器3、....组件生命周期详细:https://www.cnblogs.com/wangjiachen666/p/9497749.html使用this.$once参考:https://...
·
问题描述:有A、B两个子组件,通过component进行切换,子组件中有定时器,当切换组件时需要把定时器给注销掉。
1、通过VUE组件生命周期进行删除定时器
2、使用this.$once来监听定时器
3、....
组件生命周期详细:https://www.cnblogs.com/wangjiachen666/p/9497749.html
使用this.$once参考:https://juejin.im/post/5cc17b88f265da03705fbbbe
以下测试代码,其中A.vue为生命周期删除,B.vue为this.$once监听删除
Test.vue
<template>
<div id="testdiv">
<component ref="a" :is="assembly" :key="assembly"></component>
<ul>
<li
class="basis"
v-for="(item,index) in submenuarr"
:key="index"
@click="SwitchPath(item,index)"
:class="{on:cur==index}"
>
{{item}}
</li>
</ul>
</div>
</template>
<script>
import taba from './A'
import tabb from './B'
export default {
components: { taba, tabb },
props: {},
data() {
return {
assembly: 'taba', //默认a
cur: 0,
submenuarr: ['taba', 'tabb'], //子菜单
}
},
watch: {},
computed: {},
methods: {
//初始化子菜单
init() {
var arr = ['taba', 'tabb']
this.submenuarr = arr
},
//子菜单切换
SwitchPath(name, number) {
const _this = this
_this.assembly = name //切换
_this.cur = number
},
},
created() {},
mounted() {
},
}
</script>
<style scoped>
#testdiv{
background-color: #ffffff;
}
</style>
A.vue
<template>
<p>这是A页面,测试:{{num}}</p>
</template>
<script>
export default {
name: 'A',
data() {
return {
interval: '',
num: 0,
}
},
mounted() {
this.interval= setInterval(() => {
this.num++
},1000);
},
beforeDestroy:function(){//beforeDestory:销毁前执行($destroy方法被调用的时候就会执行),一般在这里善后:清除计时器、清除非指令绑定的事件等等...
console.log("A页面beforeDestroy清除定时器");
clearInterval(this.interval)
},
}
</script>
<style scoped>
</style>
B.vue
<template>
<p>这是B页面,测试{{num}}</p>
</template>
<script>
export default {
name: 'B',
data() {
return {
interval: '',
num: 1000,
}
},
mounted() {
const timer = setInterval(() =>{
this.num+=500
}, 1000);
// 通过$once来监听定时器
// 在beforeDestroy钩子触发时清除定时器
this.$once('hook:beforeDestroy', () => {
console.log("this.$once监听定时器")
clearInterval(timer);
})
},
}
</script>
<style scoped>
</style>
效果:
如果在comprnent组件外加上keep-alive后,上述的删除定时器方法就会失效了。
参考:http://www.3qphp.com/web/javascript/5103.html
测试代码新增C.vue,并且comprnent组件外加上keep-alive
<template>
<p>这是C页面,测试:{{cnum}}</p>
</template>
<script>
export default {
name: 'C',
data() {
return {
interval: '',
cnum: 0,
}
},
methods: {
},
mounted() {
},
beforeDestroy:function(){//beforeDestory:销毁前执行($destroy方法被调用的时候就会执行),一般在这里善后:清除计时器、清除非指令绑定的事件等等...
console.log("C页面beforeDestroy清除定时器");
clearInterval(this.interval)
},
activated(){//缓存的组件重新激活时调用
this.interval= setInterval(() => {
this.cnum+=100000
console.log("cnum+=100000",this.cnum)
},1000);
console.log("activated重新激活,cnum="+this.cnum)
},
deactivated(){//缓存的组件停用时调用
clearInterval(this.interval)
console.log("deactivated暂停,cnum="+this.cnum)
}
}
</script>
<style scoped>
</style>
效果展示
如有问题,欢迎指正!毕竟我只是个打杂的!
更多推荐
已为社区贡献1条内容
所有评论(0)