最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Vue3實現(xiàn)SSE連接的實現(xiàn)示例

 更新時間:2025年09月04日 09:38:15   作者:自信的飛  
SSE是一種允許服務(wù)器向瀏覽器推送事件的技術(shù),與WebSocket不同,SSE 是單向的,本文就來介紹了Vue3實現(xiàn)SSE連接的實現(xiàn)示例,具有一定的參考價值,感興趣都可以了解一下

在現(xiàn)代 web 開發(fā)中,Server-Sent Events (SSE) 是一種輕量級的技術(shù),允許服務(wù)器通過 HTTP 持久連接向客戶端推送實時更新。在本文中,我們將探討如何在 Vue 3 應(yīng)用中實現(xiàn) SSE 連接,并處理接收到的消息。

什么是 SSE?

SSE 是一種允許服務(wù)器向瀏覽器推送事件的技術(shù)。與 WebSocket 不同,SSE 是單向的:服務(wù)器可以向客戶端發(fā)送數(shù)據(jù),而客戶端不能直接向服務(wù)器發(fā)送數(shù)據(jù)。SSE 適用于需要實時更新的應(yīng)用,比如聊天應(yīng)用、通知系統(tǒng)和實時數(shù)據(jù)監(jiān)控。

核心代碼示例:

    let retryCount = 0;
    const maxRetries = 5; // 最大重試次數(shù)
    const maxRetryDelay = 30000; // 最大重連時間,30秒  

    // 當(dāng)前用戶身份
    const username = ref("");

    // 初始化 SSE 連接
    let eventSource: EventSource;
    const initializeSSE = () => {
      // 連接SSE
      // 定義SSE鏈接參數(shù)
      let url =
        import.meta.env.VITE_BASE_API +
        "/notification/socket_connection?username=" +
        encodeURIComponent(username.value);
      // 監(jiān)聽連接打開事件
      eventSource = new EventSource(url);
      eventSource.onopen = () => {
        console.log("建立 SSE 連接成功");
      };

      // 監(jiān)聽消息事件
      eventSource.onmessage = event => {
        // 收到消息
        chunk.value = JSON.parse(event.data);
        console.log("收到的類型:", chunk.value.notice_type, 222);

        // 根據(jù) notice_type 處理不同的通知類型
        switch (chunk.value.notice_type) {
          case 0:
            userThumNotification();
            break;
          case 1:
            userStarNotification();
            break;
          case 2:
            userComNotification();
            break;
          case 3:
            systemNotice();
            break;
          case 4:
            managerNotice();
            break;
          case 5:
            // 暫時擱置,用其他方法代替
            if (storedRole.value !== "user") {
              reportEmail();
            }
            break;
          default:
            console.warn("未知通知類型:", chunk.value.notice_type);
        }
        showNotify();
      };

      // 監(jiān)聽錯誤事件
      eventSource.onerror = () => {
        console.error("SSE 連接發(fā)生錯誤,嘗試重連...");
        eventSource.close(); // 關(guān)閉當(dāng)前連接
        handleReconnect(); // 嘗試重連
      };
    };

    const handleReconnect = () => {
      if (username.value !== "") {
        console.log("連接已關(guān)閉, 嘗試重新連接");
        if (retryCount < maxRetries) {
          retryCount++;
          const retryDelay = Math.min(
            1000 * Math.pow(2, retryCount),
            maxRetryDelay
          ); // 計算重連延遲
          setTimeout(initializeSSE, retryDelay);
        } else {
          showToast("網(wǎng)絡(luò)連接不穩(wěn)定,請檢查網(wǎng)絡(luò)或重新登錄。");
          console.log("已達到最大重試次數(shù),停止重連。");
        }
      }
    };

舉例:全局狀態(tài)管理消息總數(shù)

假設(shè)我們有三種通知類型:

點贊、評論、收藏

在userStore中進行全局狀態(tài)管理,動態(tài)更新消息數(shù)量:

import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { getManagerNotification } from "@/api/user";
import { getreportEmail } from "@/api/user";
import { getSystemNotification } from "@/api/user";
import {
  getUserThumNotification,
  getUserComNotification,
  getUserStarNotification
} from "@/api/user";
import { showToast } from "vant";
// import { showNotify } from "vant";
//用戶信息管理
export const useInformation = defineStore(
  "notication",
  () => {
    let retryCount = 0;
    const maxRetries = 5; // 最大重試次數(shù)
    const maxRetryDelay = 30000; // 最大重連時間,30秒

    // 是否顯示SSE彈框
    const noticeShow = ref(false);
    // 接收到的SSE消息
    const chunk = ref();

    // 當(dāng)前用戶身份
    const username = ref("");
    const storedRole = ref("");

    // 系統(tǒng)最新一條通知
    const systemData = ref({});
    // 管理員最新一條通知
    const managerData = ref({});

    // 用戶未讀消息
    const thumb = ref(0);
    const comment = ref(0);
    const star = ref(0);
    // 管理員未讀消息數(shù)
    const manager_count = ref(0);
    // 系統(tǒng)未讀消息數(shù)
    const system_count = ref(0);
    // 郵箱未讀消息數(shù)
    const email_count = ref(0);

    // 互動通知
    // 默認活躍的tab欄
    const activeTab = ref(0);

    // 總數(shù)
    // 使用計算屬性動態(tài)獲取 total
    const total = computed(() => {
      return (
        thumb.value +
        comment.value +
        star.value +
        manager_count.value +
        system_count.value
      );
    });

    // 通用的獲取未讀通知數(shù)量的函數(shù)
    const fetchNotificationCount = async (fetchFunction, refData, refCount) => {
      try {
        const res = await fetchFunction({ page: 1, limit: 1 });
        if (refData != null) {
          refData.value = res.data;
        }
        refCount.value = res.data.unread_count;
      } catch (error) {
        console.error("獲取通知時發(fā)生錯誤:", error);
      }
    };

    // 獲取系統(tǒng)消息
    const systemNotice = () => {
      fetchNotificationCount(getSystemNotification, systemData, system_count);
      console.log(system_count.value);
    };

    // 獲取管理員消息
    const managerNotice = () => {
      fetchNotificationCount(
        getManagerNotification,
        managerData,
        manager_count
      );
    };

    // 獲取點贊通知的未讀消息數(shù)量
    const userThumNotification = () => {
      fetchNotificationCount(getUserThumNotification, null, thumb);
    };

    // 獲取評論通知的未讀消息數(shù)量
    const userComNotification = () => {
      fetchNotificationCount(getUserComNotification, null, comment);
    };

    // 獲取收藏通知的未讀消息數(shù)量
    const userStarNotification = () => {
      fetchNotificationCount(getUserStarNotification, null, star);
    };

    // 獲取舉報郵箱消息
    const reportEmail = async () => {
      fetchNotificationCount(getreportEmail, null, email_count);
    };

    // 獲取頁面消息
    const userNotice = async () => {
      await Promise.all([
        userThumNotification(),
        userComNotification(),
        userStarNotification()
      ]);
    };

    // 初始化函數(shù)
    const initNotifications = () => {
      console.log(username, "哈哈哈紅紅火火恍恍惚惚");
      systemNotice();
      managerNotice();
      userNotice();
      if (storedRole.value !== "user") {
        reportEmail();
      }
      // 打印 total,確保它是最新的
      console.log("Total after initialization:", total.value);
    };

    const showNotify = () => {
      noticeShow.value = true;
      setTimeout(() => {
        noticeShow.value = false;
      }, 3000);
    };

    // 初始化 SSE 連接
    let eventSource: EventSource;
    const initializeSSE = () => {
      // 連接SSE
      // 定義SSE鏈接參數(shù)
      let url =
        import.meta.env.VITE_BASE_API +
        "/notification/socket_connection?username=" +
        encodeURIComponent(username.value);
      // 監(jiān)聽連接打開事件
      eventSource = new EventSource(url);
      eventSource.onopen = () => {
        console.log("建立 SSE 連接成功");
      };

      // 監(jiān)聽消息事件
      eventSource.onmessage = event => {
        // 收到消息
        chunk.value = JSON.parse(event.data);
        console.log("收到的類型:", chunk.value.notice_type, 222);

        // 根據(jù) notice_type 處理不同的通知類型
        switch (chunk.value.notice_type) {
          case 0:
            userThumNotification();
            break;
          case 1:
            userStarNotification();
            break;
          case 2:
            userComNotification();
            break;
          case 3:
            systemNotice();
            break;
          case 4:
            managerNotice();
            break;
          case 5:
            // 暫時擱置,用其他方法代替
            if (storedRole.value !== "user") {
              reportEmail();
            }
            break;
          default:
            console.warn("未知通知類型:", chunk.value.notice_type);
        }
        showNotify();
      };

      // 監(jiān)聽錯誤事件
      eventSource.onerror = () => {
        console.error("SSE 連接發(fā)生錯誤,嘗試重連...");
        eventSource.close(); // 關(guān)閉當(dāng)前連接
        handleReconnect(); // 嘗試重連
      };
    };

    const handleReconnect = () => {
      if (username.value !== "") {
        console.log("連接已關(guān)閉, 嘗試重新連接");
        if (retryCount < maxRetries) {
          retryCount++;
          const retryDelay = Math.min(
            1000 * Math.pow(2, retryCount),
            maxRetryDelay
          ); // 計算重連延遲
          setTimeout(initializeSSE, retryDelay);
        } else {
          showToast("網(wǎng)絡(luò)連接不穩(wěn)定,請檢查網(wǎng)絡(luò)或重新登錄。");
          console.log("已達到最大重試次數(shù),停止重連。");
        }
      }
    };

    // 關(guān)閉 SSE 連接
    const closeConnection = () => {
      eventSource.close();
      console.log("SSE 連接已手動關(guān)閉");
    };

    // 重置
    const removeNotification = () => {
      systemData.value = {};
      managerData.value = {};
      thumb.value = 0;
      star.value = 0;
      manager_count.value = 0;
      system_count.value = 0;
      email_count.value = 0;
      activeTab.value = 0;
    };

    return {
      username,
      storedRole,
      systemData,
      managerData,
      manager_count,
      system_count,
      email_count,
      thumb,
      comment,
      star,
      total,
      activeTab,
      noticeShow,
      chunk,
      systemNotice,
      managerNotice,
      userThumNotification,
      userComNotification,
      userStarNotification,
      reportEmail,
      closeConnection,
      removeNotification,
      initializeSSE,
      initNotifications
    };
  },
  {
    persist: true
  }
);

到此這篇關(guān)于Vue3實現(xiàn)SSE連接的實現(xiàn)示例的文章就介紹到這了,更多相關(guān)Vue3 SSE連接內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • vue組件間屬性傳值的常用的方法和規(guī)范詳解

    vue組件間屬性傳值的常用的方法和規(guī)范詳解

    在Vue?CLI項目中,組件間的屬性傳值是一個常見的需求,本文為大家整理了一些常用的傳值方法和規(guī)范以及相應(yīng)的代碼演示和解說,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2025-05-05
  • 超詳細的vue組件間通信總結(jié)

    超詳細的vue組件間通信總結(jié)

    作為一個vue初學(xué)者不得不了解的就是組件間的數(shù)據(jù)通信(暫且不談vuex),通信方式根據(jù)組件之間的關(guān)系有不同之處,這篇文章主要給大家介紹了關(guān)于vue組件間通信的相關(guān)資料,需要的朋友可以參考下
    2021-07-07
  • vue-simple-uploader上傳成功之后的response獲取代碼

    vue-simple-uploader上傳成功之后的response獲取代碼

    這篇文章主要介紹了vue-simple-uploader上傳成功之后的response獲取代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧~
    2020-09-09
  • 關(guān)于elementUi表格合并行數(shù)據(jù)并展示序號

    關(guān)于elementUi表格合并行數(shù)據(jù)并展示序號

    這篇文章主要介紹了關(guān)于elementUi表格合并行數(shù)據(jù)并展示序號,通過給table傳入span-method方法可以實現(xiàn)合并行或列,方法的參數(shù)是一個對象,感興趣的朋友可以學(xué)習(xí)一下
    2023-04-04
  • vue用戶長時間不操作退出到登錄頁的兩種實現(xiàn)方式

    vue用戶長時間不操作退出到登錄頁的兩種實現(xiàn)方式

    出于安全考慮,用戶長時間不操作,就回到登錄頁面,讓用戶重新登錄,本文就記錄一下實現(xiàn)這種效果的兩種方式,具有一定的參考價值,感興趣的可以了解一下
    2021-09-09
  • Vue的實例、生命周期與Vue腳手架(vue-cli)實例詳解

    Vue的實例、生命周期與Vue腳手架(vue-cli)實例詳解

    本文通過實例代碼+圖片描述的形式給大家介紹了Vue的實例、生命周期與Vue腳手架(vue-cli)知識,需要的朋友可以參考下
    2017-12-12
  • Vue頁面渲染中key的應(yīng)用實例教程

    Vue頁面渲染中key的應(yīng)用實例教程

    這篇文章主要給大家介紹了關(guān)于Vue頁面渲染中key的應(yīng)用的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • Vue3.0 自己實現(xiàn)放大鏡效果案例講解

    Vue3.0 自己實現(xiàn)放大鏡效果案例講解

    這篇文章主要介紹了Vue3.0 自己實現(xiàn)放大鏡效果案例講解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下
    2021-07-07
  • vue中子組件傳遞數(shù)據(jù)給父組件的講解

    vue中子組件傳遞數(shù)據(jù)給父組件的講解

    今天小編就為大家分享一篇關(guān)于vue中子組件傳遞數(shù)據(jù)給父組件的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-01-01
  • vue-quill-editor 自定義工具欄和自定義圖片上傳路徑操作

    vue-quill-editor 自定義工具欄和自定義圖片上傳路徑操作

    這篇文章主要介紹了vue-quill-editor 自定義工具欄和自定義圖片上傳路徑操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-08-08

最新評論

吕梁市| 西安市| 兴义市| 沂源县| 黔西县| 普安县| 静乐县| 扶余县| 金秀| 山东省| 溆浦县| 高淳县| 宝鸡市| 巴楚县| 高陵县| 胶南市| 涞水县| 壤塘县| 马鞍山市| 营山县| 望奎县| 错那县| 望都县| 高台县| 凤凰县| 志丹县| 遂平县| 汉川市| 麻江县| 布尔津县| 东莞市| 杭锦后旗| 德兴市| 惠州市| 叶城县| 五莲县| 册亨县| 诸城市| 巨野县| 贵溪市| 太原市|