eventSource.vue 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <!--
  2. * @Author: HTangtang 1539880046@qq.com
  3. * @Date: 2025-01-21 14:41:20
  4. * @LastEditors: HTangtang 1539880046@qq.com
  5. * @LastEditTime: 2025-03-06 17:49:40
  6. * @FilePath: \dam_app_project\pages\smartAi\components\eventSource.vue
  7. * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
  8. -->
  9. <template>
  10. <view id="event-source" :props="mergeProps" :change:props="eventSource.renderPropsChange" v-show="false">
  11. </view>
  12. </template>
  13. <script>
  14. export default {
  15. props: {
  16. url: {
  17. type: String,
  18. default: "",
  19. },
  20. options: {
  21. type: Object,
  22. default: () => ({}),
  23. },
  24. },
  25. data() {
  26. return {
  27. isSend: false
  28. }
  29. },
  30. computed: {
  31. // 合并传入renderjs的数据
  32. mergeProps({ url, options, isSend }) {
  33. return {
  34. url,
  35. options,
  36. isSend
  37. };
  38. },
  39. },
  40. methods: {
  41. // 发送
  42. send() {
  43. this.isSend = true;
  44. this.$nextTick(() => {
  45. this.isSend = false;
  46. });
  47. },
  48. // 处理renderjs发回的数据
  49. emits(e) {
  50. this.$emit("callback", { ...e });
  51. },
  52. },
  53. };
  54. </script>
  55. <script module="eventSource" lang="renderjs">
  56. import { fetchEventSource } from "@microsoft/fetch-event-source";
  57. export default {
  58. methods: {
  59. // 传入数据变更
  60. renderPropsChange(nVal) {
  61. const { url, isSend } = nVal || {};
  62. if (!isSend) return;
  63. if (!url) return this.handleEmitData({ type: "tip", msg: "URL cannot be empty." });
  64. this.$nextTick(() => {
  65. this.handleSSE(nVal);
  66. });
  67. },
  68. // 发送数据到service层
  69. handleEmitData(data = {}) {
  70. this.$ownerInstance.callMethod('emits', data);
  71. },
  72. // 处理SSE
  73. handleSSE(opts = {}) {
  74. const that = this;
  75. // 检查浏览器是否支持SSE
  76. if (!('EventSource' in window)) return this.handleEmitData({ type: "tip", msg: "The current device does not support EventSource." });
  77. const { url, options = {} } = opts || {};
  78. // console.log("options", JSON.stringify(options));
  79. fetchEventSource(url, {
  80. ...options,
  81. async onopen() {
  82. that.handleEmitData({ type: "onopen", msg: "EventSource onopen." });
  83. },
  84. onmessage(res) {
  85. // console.log(res,'resres')
  86. that.handleEmitData({ type: "onmessage", msg: "EventSource onmessage.", data: res.data });
  87. },
  88. onclose() {
  89. that.handleEmitData({ type: "onclose", msg: "EventSource onclose." });
  90. },
  91. onerror(error) {
  92. that.handleEmitData({ type: "onerror", msg: "EventSource onerror.", data: JSON.stringify(error) });
  93. }
  94. });
  95. }
  96. }
  97. }
  98. </script>