|
@@ -0,0 +1,83 @@
|
|
|
+<template>
|
|
|
+ <el-popover placement="bottom" :width="310" trigger="click">
|
|
|
+ <template #reference>
|
|
|
+ <div class="menu--message-trigger">
|
|
|
+ <el-tooltip :content="$t('le.message.txt')" effect="dark" placement="bottom">
|
|
|
+ <div class="menu--message menu-item le-hover-effect--bg">
|
|
|
+ <el-badge :value="90" :max="99">
|
|
|
+ <i class="le-iconfont le-notice"></i>
|
|
|
+ </el-badge>
|
|
|
+ </div>
|
|
|
+ </el-tooltip>
|
|
|
+ </div>
|
|
|
+ </template>
|
|
|
+ <ul>
|
|
|
+ <li v-for="(item, idx) in receivedData" :key="idx"> {{ item }}</li>
|
|
|
+ </ul>
|
|
|
+ </el-popover>
|
|
|
+</template>
|
|
|
+<script setup>
|
|
|
+import { onMounted, ref, onBeforeUnmount } from 'vue';
|
|
|
+import {ls} from "@/utils";
|
|
|
+const token = ls.get('token')
|
|
|
+const { VITE_APP_BASE_API } = import.meta.env;
|
|
|
+// const serviceUrlApi = ref(`${VITE_APP_BASE_API}/sys/sse/connect`);
|
|
|
+const serviceUrlApi = ref(`http://localhost:3000/events`);
|
|
|
+let sseService = ref(null);
|
|
|
+let receivedData = ref([])
|
|
|
+
|
|
|
+// 创建一个新的 EventSource,但首先使用 fetch API 发送带有 Authorization 头的请求
|
|
|
+function connectSSEWithHeaders(url, headers = {}) {
|
|
|
+ return fetch(url, {
|
|
|
+ method: 'GET',
|
|
|
+ headers: headers,
|
|
|
+ cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
|
|
|
+ mode: 'cors', // no-cors, cors, *same-origin
|
|
|
+ credentials: 'same-origin', // include, *same-origin, omit
|
|
|
+ redirect: 'follow', // manual, *follow, error
|
|
|
+ referrerPolicy: 'no-referrer', // no-referrer, *client
|
|
|
+ })
|
|
|
+ .then(response => {
|
|
|
+ if (!response.ok) {
|
|
|
+ throw new Error('Network response was not ok');
|
|
|
+ }
|
|
|
+ return new EventSource(url);
|
|
|
+ // 读取响应体作为文本,然后解析URL来创建 EventSource
|
|
|
+ // const t = response.json()
|
|
|
+ // console.log(t);
|
|
|
+ // return response.text().then(text => {
|
|
|
+ // console.info('text', text)
|
|
|
+ // // 这里通常不需要解析text,因为我们只是要确认连接成功。
|
|
|
+ // // 但如果SSE URL在响应体中,你可能需要处理它。
|
|
|
+ // // 假设服务器直接支持SSE在原始URL
|
|
|
+ //
|
|
|
+ // });
|
|
|
+ })
|
|
|
+ .catch(error => {
|
|
|
+ console.error('There was a problem with your fetch operation:', error);
|
|
|
+ });
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+onMounted(() => {
|
|
|
+ connectSSEWithHeaders(serviceUrlApi.value, { 'accessToken': token })
|
|
|
+ .then(eventSource => {
|
|
|
+ sseService = eventSource
|
|
|
+ eventSource.onmessage = function(e) {
|
|
|
+ console.log(e, '----====----');
|
|
|
+ console.log('后端返回的数据:', e.data);
|
|
|
+ receivedData.value.push(e.data)
|
|
|
+ }
|
|
|
+ eventSource.onerror = function(err) {
|
|
|
+ console.error('EventSource failed:', err);
|
|
|
+ };
|
|
|
+ })
|
|
|
+})
|
|
|
+
|
|
|
+onBeforeUnmount(() => {
|
|
|
+ if (sseService) {
|
|
|
+ sseService.close();
|
|
|
+ sseService = null;
|
|
|
+ }
|
|
|
+});
|
|
|
+</script>
|