123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155 |
- 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')
- )
- ])
- ]
- )
- });
- }
- };
|