首页 >> js开发 >> js浅谈vue 组件中的setInterval方法和window的不同js大全
js浅谈vue 组件中的setInterval方法和window的不同js大全
发布时间: 2021年1月13日 | 浏览:
| 分类:js开发
vue组件中,this指向实例,【实例中重写了setInterval等一整套方法】。所以,千万不能和 window 下挂载的方法混用具体不同在于,window.setInterval执行完比后返回一个id,而vue实例中返回【定时器对象】,当然该对象中包含一个_id的私有属性因为 clearInterval 方法参数是id,所以最佳实践是统一使用 window 的方法,不要使用 vue组件的方法vue中的定时器方法,要使用箭头函数,不要出现 const that = this 的写法
//正确的用法
mounted() {
// 如果不加 window ,则会使用 vue实例的方法,将无法清除定时器
this.timer = window.setInterval(() => {
this.date = new Date();
}, 2000);
console.log(this.timer);//number
},
methods: {
clearTimer() {
window.clearInterval(this.timer);
this.timer = null;
}
}
//正确的用法
mounted() {
// 如果不加 window ,则会使用 vue实例的方法,将无法清除定时器
this.timer = window.setInterval(() => {
this.date = new Date();
}, 2000);
console.log(this.timer);//number
},
methods: {
clearTimer() {
window.clearInterval(this.timer);
this.timer = null;
}
}
补充知识:vue 切换页面 setInterval补充知识:补充知识:vue 切换页面 setIntervalvue 是单页面应用,路由切换后,定时器并不会自动关闭,需要手动清除,当页面被销毁时,清除定时器即可。
mounted(){
clearInterval(this.timer);
this.setTimer();
},
destroyed(){
clearInterval(this.timer)
}
mounted(){
clearInterval(this.timer);
this.setTimer();
},
destroyed(){
clearInterval(this.timer)
}以上这篇浅谈vue 组件中的setInterval方法和window的不同就是小编分享给大家的全部内容了,希望能给大家一个参考。
//正确的用法
mounted() {
// 如果不加 window ,则会使用 vue实例的方法,将无法清除定时器
this.timer = window.setInterval(() => {
this.date = new Date();
}, 2000);
console.log(this.timer);//number
},
methods: {
clearTimer() {
window.clearInterval(this.timer);
this.timer = null;
}
}
//正确的用法
mounted() {
// 如果不加 window ,则会使用 vue实例的方法,将无法清除定时器
this.timer = window.setInterval(() => {
this.date = new Date();
}, 2000);
console.log(this.timer);//number
},
methods: {
clearTimer() {
window.clearInterval(this.timer);
this.timer = null;
}
}
补充知识:vue 切换页面 setInterval补充知识:补充知识:vue 切换页面 setIntervalvue 是单页面应用,路由切换后,定时器并不会自动关闭,需要手动清除,当页面被销毁时,清除定时器即可。
mounted(){
clearInterval(this.timer);
this.setTimer();
},
destroyed(){
clearInterval(this.timer)
}
mounted(){
clearInterval(this.timer);
this.setTimer();
},
destroyed(){
clearInterval(this.timer)
}以上这篇浅谈vue 组件中的setInterval方法和window的不同就是小编分享给大家的全部内容了,希望能给大家一个参考。
相关文章:
- js代码javascript实现时间日期的格式化的方法汇总
- jsvant 自定义 van-dropdown-item的用法js大全
- jsJS事件循环机制event loop宏任务微任务原理解析js大全
- js解决vue addRoutes不生效问题js大全
- jsvue 解决addRoutes多次添加路由重复的操作js大全
- jsvue相同路由跳转强制刷新该路由组件操作js大全
- jsantd vue 刷新保留当前页面路由,保留选中菜单,保留menu选中操作js大全
- jsvue实现在进行增删改操作后刷新页面js大全
- js解决vue项目input输入框双向绑定数据不实时生效问题js大全
- js代码详解vue路由,js详解vue路由