定时器是个好东西
当你需要在一个组件初始化时获取父组件的数据并且操作它,使用watch会操作多次,在mounted里面第二次进入就不会再调用了,那么这时候就可以使用定时器了。
mounted(){
this.createEvents()
}
createEvents() {
if (this.eventEmitter) {
this.eventEmitter.on(EventType.SUBMIT_SECUID_LIST, this.handleValidateForm); // 表单校验
} else {
setTimeout(() => {
this.createEvents();
}, 300);
}
}
当你需要计算页面的高度而苦于不知道组件有没有渲染时,定时器它又可以派上用场了
mounted(){
this.calcHeight()
}
calcHeight() {
if (this.$refs.table) {
//
const height = this.$refs.table.clientHeight;
} else {
setTimeout(() => {
this.calcHeight();
}, 300);
}
}
本文介绍了如何利用定时器解决前端开发中常见的问题,如组件初始化时的数据操作及页面高度计算等。通过具体实例展示了定时器在提升用户体验方面的应用。
1万+





