vue 中添加全局轮询消息刷新
场景:后台有消息更新,但不会主动推送给前端,需要前端实时刷新,获取最新的消息提示

思路:后台每个页面通常都会有 layout 组件,我这里写在 header.vue 中,只要登录成功,
在 mounted 中编写代码,采用 hook 写法,在同一个地方编写,逻辑较为清晰。
进入 header 相关页面,就开始执行定时器,退出登录,清除定时器,上代码
mounted() { // 开启消息定时器 let messageTimer = setInterval(() => { that.getnotice(); }, 50000); this.$on('hook:beforeDestroy', () => { // 清除消息定时器 clearInterval(messageTimer); messageTimer = null; }); let that = this; this.$on('hook:activated', () => { if (messageTimer === null) { // 避免重复开启消息定时器 messageTimer = setInterval(() => { that.getnotice(); }, 50000); } }); this.$on('hook:deactivated', () => { // 清楚消息定时器 clearInterval(messageTimer); messageTimer = null; }); }

浙公网安备 33010602011771号