connect-event-source.uvue 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <template>
  2. <page-head :title="title"></page-head>
  3. <button class="button" type="primary" @click="connect">连接</button>
  4. <button class="button" type="primary" @click="close">关闭</button>
  5. <!-- #ifdef APP -->
  6. <scroll-view style="flex:1">
  7. <!-- #endif -->
  8. <view>
  9. <text style="width: 100%; text-align: center; margin-bottom: 5px;">
  10. 显示简易操作日志(可滚动查看)
  11. </text>
  12. <button size="mini" @click="logList = []">清空日志</button>
  13. <view style="margin-top: 10px;">
  14. <view v-for="(item, index) in logList" :key="index">
  15. <text style="margin-left: 20px; margin-right: 20px;">
  16. {{ item }}
  17. </text>
  18. </view>
  19. </view>
  20. </view>
  21. <!-- #ifdef APP -->
  22. </scroll-view>
  23. <!-- #endif -->
  24. </template>
  25. <script>
  26. export default {
  27. data() {
  28. return {
  29. logList: [] as string[],
  30. title: 'sse',
  31. url: 'https://request.dcloud.net.cn/api/sse/connect',
  32. eventSource: null as UniEventSource | null,
  33. open: false,
  34. receiveMessage: false
  35. }
  36. },
  37. unmounted() {
  38. if (this.eventSource != null) {
  39. this.eventSource?.close()
  40. }
  41. },
  42. methods: {
  43. connect() {
  44. console.log('connect start')
  45. uni.showLoading({
  46. title: "",
  47. mask: true
  48. })
  49. this.eventSource?.close()
  50. let headers : UTSJSONObject = new UTSJSONObject()
  51. headers.set("header1", "value1")
  52. headers.set("header2", "value3")
  53. this.eventSource = uni.connectEventSource({
  54. url: this.url,
  55. header: headers
  56. })
  57. this.eventSource?.onMessage((ev) => {
  58. const log = 'onMessage callback:' + '\n' + 'type: ' + ev.type + '\n' + 'data: ' + ev.data + '\n\n'
  59. this.logList.push(log)
  60. this.receiveMessage = true
  61. uni.hideLoading()
  62. })
  63. this.eventSource?.onOpen((ev) => {
  64. const log = 'onOpen callback: ' + ev.type + '\n\n'
  65. this.logList.push(log)
  66. this.open = true
  67. })
  68. this.eventSource?.onError((err) => {
  69. const log = `onError callback: ${err} \n\n`
  70. this.logList.push(log)
  71. uni.hideLoading()
  72. })
  73. },
  74. close() {
  75. this.eventSource?.close()
  76. const log = 'connect close' + '\n\n'
  77. this.logList.push(log)
  78. }
  79. }
  80. }
  81. </script>
  82. <style>
  83. .button {
  84. margin-left: 30px;
  85. margin-right: 30px;
  86. margin-bottom: 15px;
  87. }
  88. </style>