soketMixin.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import WebSocketManager from '@/utils/WebSocketManager.js';
  2. import store from '@/store'
  3. import { getToken } from '@/utils/auth'
  4. export default {
  5. data() {
  6. return {
  7. // userId: store.state.user.userId,
  8. // ws: store.state.user.wsManager
  9. }
  10. },
  11. onShow: function () {
  12. uni.loadFontFace({
  13. family: "uicon-iconfont",
  14. source: 'url("https://at.alicdn.com/t/font_2225171_8kdcwk4po24.ttf")',
  15. global: true,
  16. success: (success) => {
  17. console.log("Font loaded successfully", success);
  18. },
  19. fail: (fail) => {
  20. console.log("Font loading failed", fail);
  21. },
  22. });
  23. uni.$u.connectSoket = this.connectSoket;
  24. uni.$u.closeSoket = this.closeSoket;
  25. uni.$u.debounce(this.connectSoket(), 500)
  26. },
  27. onHide: function () {
  28. this.closeSoket();
  29. },
  30. methods: {
  31. connectSoket(user_id){
  32. const ws = store.state.user.wsManager;
  33. const userId = user_id || uni.getStorageSync('userId');
  34. const token = getToken();
  35. if (!ws && userId && token) {
  36. // 获取账户时,连接soket
  37. const ms = new WebSocketManager(userId);
  38. // 设置消息回调
  39. ms.onMessage(data => {
  40. // 处理消息逻辑
  41. if (data.type === 'msgUnreadCount') {
  42. store.dispatch('handleMessageCount',data.data);
  43. }
  44. });
  45. // 建立连接
  46. ms.connect();
  47. store.dispatch('handleSoket',ms);
  48. }
  49. },
  50. closeSoket(){
  51. const ws = store.state.user.wsManager;
  52. if(ws){
  53. ws.closeConnection();
  54. }
  55. }
  56. }
  57. }