vue页面的定时刷新
setInterval
setInterval以指定时间为周期循环执行,一般用于刷新表单,对于一些表单的假实时指定时间刷新同步
在做一个项目的时候,会遇到要求一个页面几分钟去定时刷新一下获取最新数据的情况,需要用到 setInterval() 了,下面是自己使用的vue中查询是否有未读消息的通知的定时器。
template标签中消息通知的内容:
<div class="btn-bell">
<el-tooltip effect="dark" :content="message?`有${message}条未读消息`:`消息中心`" placement="bottom">
<router-link to="notify">
<i class="el-icon-bell"></i>
</router-link>
</el-tooltip>
<span class="btn-bell-badge" v-if="message"></span>
</div>
script标签中的部分内容
<script>
export default {
data() {
return {
message: 0, // 有几条未读的消息
timer: null // 定时器
}
},
// 每20秒刷新一次
created () {
this.timer = setInterval(() =>{
this.getNotReadCount()
},1000* 20)
},
methods:{
// 得到未读的消息个数
getNotReadCount () {
// console.log('1232143')
this.$axios.get('/api/notifications/notReadCount').then((res) =>{
if(res.data.code ===1){
this.message = res.data.data[0]
console.log('this.notifyReadCount' + this.message)
}
})
},
// 可以判断如果定时器还在运行就关闭 或者直接关闭
destroyed () {
clearInterval(this.timer)
}
}
</script>
setTimeout
只在指定时间后执行一次,一般用于延迟执行某方法或功能
<script>
//定时器 异步运行
function hello(){
alert("hello");
}
//使用方法名字执行方法
var t1 = window.setTimeout(hello,1000);
var t2 = window.setTimeout("hello()",3000);//使用字符串执行方法
window.clearTimeout(t1);//去掉定时器
</script>