1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Vue.js + Server-Sent Eventsでリアルタイム通信

Last updated at Posted at 2022-01-14

#概要
サーバーから能動的にデータを送信するHTTP通信方法であるServer-Sent Events(SSE)を利用して画面上の画像を都度差し替えて表示する仕組みを作ってみていたので覚書として。

#導入
下記のコードをvue.js内のmethodsに書き込めばおおよそ完了。
EventSourceにはリアルタイム取得したいサーバー側のURIを書き込み、Cookieも有効にしたい場合はコンマ区切りで{ withCredentials: true }を追加すればOK。

<script>
methods: {
  getImage () {
    let evtSource = new EventSource('/get_image', { withCredentials: true })
    evtSource.addEventListener('message', event => {
      this.imgSrc = event.data
    }, false)
  }
}
</script>

vueファイルの全体像としては下記のイメージ。

display.vue
<template>
  <div>
    <img :src="imgSrc"/>
  </div>
</template>

<script>
export default {
  data () {
    return {
      imgSrc: null
    }
  },
  created: function () {
    this.getImage()
  },
  methods: {
    getImage () {
      let evtSource = new EventSource('/get_image', { withCredentials: true })
      evtSource.addEventListener('message', event => {
        this.imgSrc = event.data
      }, false)
    }
  }
}
</script>
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?