关于Vue SSE(服务器推送事件)的一些问题

3

我将使用SSE实现实时通知。请查看我的方法并告诉我问题在哪里以及如何解决。

在vuex登录操作方法中

// SSE EvnetSource Connect
      let url = process.env.VUE_APP_API_URL + "subscribe";
      let eventSource = new EventSource(url, {
        withCredentials: true
      });
      eventSource.addEventListener("notification", function (event) {
        console.log(event.data);
        commit('setNotification', event.data) // => set event's data to vuex 'notification' state as array
      });

然后

在顶部导航组件的 watch 方法中

watch: {
  notification(val) {
    if(val) {
      const notiData = JSON.parse(val)
      if(notiData.id) {
        // show notification alert component 
        this.$notify("info filled", "notification", notiData.content, null, {
          duration: 7000,
          permanent: false
        });
      }
    }
  }

这是我的当前情况。

以下是我的问题:

  1. 目前,在通过vuex登录时,我创建了一个EventSource,但是注销时如何删除EventSource?(EventSource没有全局定义,所以我不知道在注销时如何处理它。)

  2. 如何在页面刷新后重新连接EventSource?(我认为main.js可以处理它。)

  3. 是否有办法在创建EventSource时放入自定义头?

1个回答

3
与其他事件总线一样,EventSource在不需要接收事件时需要取消订阅。这需要保留对监听器函数的引用。如果监听器使用了 Vuex 上下文,该上下文可在操作内部使用,应在登录操作中定义并存储在状态中:
  const notificationListener = (event) => {...};
  eventSource.addEventListener("notification", notificationListener);

  // can be moved to a mutation
  state._notificationEventSource = eventSource;
  state._notificationListener = notificationListener;

登出操作内部:

let { _notificationEventSource: eventSource, _notificationListener: notificationListener } = state;
eventSource.removeEventListener("notification", notificationListener);

当页面首次加载和重新加载时,没有任何区别。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接