stomp.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * 基于WebStomp的消息处理插件
  3. */
  4. import Vue from 'vue';
  5. import _ from 'lodash';
  6. import assert from 'assert';
  7. import { Client } from '@stomp/stompjs/esm5/client';
  8. const Plugin = {
  9. install(Vue, options) {
  10. assert(_.isObject(options));
  11. if (options.debug && !_.isFunction(options.debug)) {
  12. options.debug = str => {
  13. console.log(str);
  14. };
  15. }
  16. assert(_.isString(options.brokerURL));
  17. if (!options.brokerURL.startsWith('ws://')) {
  18. options.brokerURL = `ws://${location.host}${options.brokerURL}`;
  19. }
  20. // 3. 注入组件
  21. Vue.mixin({
  22. beforeDestroy: function() {
  23. if (this.$stompClient) {
  24. this.$stompClient.deactivate();
  25. delete this.$stompClient;
  26. }
  27. },
  28. });
  29. // 4. 添加实例方法
  30. Vue.prototype.$stomp = function(subscribes = {}) {
  31. // connect to mq
  32. const client = new Client(options);
  33. client.onConnect = frame => {
  34. // Do something, all subscribes must be done is this callback
  35. // This is needed because this will be executed after a (re)connect
  36. console.log('[stomp] connected');
  37. Object.keys(subscribes)
  38. .filter(p => _.isFunction(subscribes[p]))
  39. .forEach(key => {
  40. client.subscribe(key, subscribes[key]);
  41. });
  42. };
  43. client.onStompError = frame => {
  44. // Will be invoked in case of error encountered at Broker
  45. // Bad login/passcode typically will cause an error
  46. // Complaint brokers will set `message` header with a brief message. Body may contain details.
  47. // Compliant brokers will terminate the connection after any error
  48. console.log('Broker reported error: ' + frame.headers['message']);
  49. console.log('Additional details: ' + frame.body);
  50. };
  51. client.activate();
  52. this.$stompClient = client;
  53. };
  54. },
  55. };
  56. export default () => {
  57. Vue.use(Plugin, Vue.config.stomp);
  58. };