import { Notification } from 'element-ui'; import i18n from './lang/index.js'; /** * 通知管理器 */ export default { // 初始化 init (vue, sessionId) { this.vue = vue; this.url = `${process.env.VUE_APP_BASE_API}/wss` this.sessionId = sessionId; this.sock = undefined; this.stomp = undefined; this.privateHandler = undefined; this.publicHandler = undefined; this.isListener = false; this._connect(); }, // 设置sessionId setSessionId (sessionId) { this.sessionId = sessionId; this.subscribePrivate(); }, // 开始监听通知 start () { this.isListener = true; }, // 结束监听通知 end () { // this._disconnect(); this.isListener = false; }, // 链接到sock服务器 _connect () { if (this.sock || this.stomp) { return; } this.sock = new window.SockJS(this.url); this.stomp = window.Stomp.over(this.sock); // 建立连接监听 this.stomp.connect( {}, frame => { console.log('con'); this.subscribePrivate(); this.subscribePublic(); }, error => { console.log('error', error); } ); }, // 断开连接 _disconnect () { this.stomp && this.stomp.disconnect(); this.sock && this.sock.close(); this.sock = undefined; this.stomp = undefined; }, // 监听私有通知 subscribePrivate () { if (this.privateHandler) { this.privateHandler.unsubscribe(); } this.privateHandler = this.stomp && this.stomp.subscribe( `/user/${this.sessionId || 'null'}/message`, response => { this.handleNotification(response); } ); }, // 监听公共通知 subscribePublic () { if (this.publicHandler) { this.publicHandler.unsubscribe(); } this.publicHandler = this.stomp && this.stomp.subscribe('/topic', response => { this.handleNotification(response); }); }, // 全部的消息都在此处处理 handleNotification (response) { if (!this.isListener) { return; } var h = this.vue.$createElement; var url = '/work/work'; var desc = ''; try { var body = JSON.parse(response.body); desc = body.msg || body.test || ''; } catch (error) { console.error(error); } Notification({ duration: 4500, type: 'warning', title: '任务', dangerouslyUseHTMLString: true, message: h( 'div', { style: { width: '240px', height: '30px', display: 'flex' } }, [ h( 'div', { style: { flex: 1, alignSelf: 'center', color: '#333' } }, desc ), h('div', { style: { alignSelf: 'center' } }, [ h( 'el-link', { attrs: { type: 'info' }, on: { click: () => { if (this.vue.$route.path === url) { // 刷新当前路由 this.vue.$children[0].reload(); } else { this.vue.$router.push(url); } } } }, i18n.t('common.viewNow') ) ]) ] ) }); } };