这篇文章看完如果您觉得有所收获,认为还行的话,就点个赞收藏一下呗
目标:接口是每10秒调用一次,所以前端这里也需要每10秒调用一次
<script>
import { GetMsgNum } from "@/api/system";
export default {
data() {
return {
value: null, //消息
timer: null, //定时器
};
},
// 轮询-
destroyed() {
//离开页面是销毁
clearInterval(this.timer);
this.timer = null;
},
created() {
this.GetMsgNum();//初始化
// 实现轮询
this.timer = window.setInterval(() => {
setTimeout(this.GetMsgNum(), 0);
}, 10000);
},
methods: {
// 轮询-------------
GetMsgNum() {
GetMsgNum({ userid: this.userid }).then((res) => {
this.value = res.data;
// console.log(res);
});
},
stop() {
clearInterval(this.timer);
this.timer = null;
},
// 轮询结束-------------
},
};
</script>