Web API 有直接支援 WebSocket,可在 Vue 內直接使用。
Version
Vue 2.7
WebSocket
<template>
<div>
<div>
<button @click="onSendMessage">
Send Message
</button>
</div>
<div>
{{ message }}
</div>
</div>
</template>
<script>
export default {
data:() => ({
connection: null,
message: '',
}),
mounted() {
this.connection = new WebSocket('wss://free.blr2.piesocket.com/v3/1?api_key=jW7aQvkMadLuZg6wdxAJsOeGHlGX8p3urLLBrZoH¬ify_self=1')
this.connection.onmessage = msg => {
console.warn('receive message', msg)
this.message = msg.data
}
this.connection.onopen = () => {
console.warn('connected to websocket server')
}
},
methods:{
onSendMessage() {
let msg = 'Hello World'
console.warn('send message', msg)
this.connection.send(msg)
}
}
}
</script>
Line 16
data:() => ({
connection: null,
message: '',
}),
connection
:儲存 WebSocket objectmessage
:儲存 WebSocket 所傳送要顯示的訊息
Line 21
this.connection = new WebSocket('wss://free.blr2.piesocket.com/v3/1?api_key=jW7aQvkMadLuZg6wdxAJsOeGHlGX8p3urLLBrZoH¬ify_self=1')
- 直接使用 new 建立 WebSocket object
- 使用免費的 PieSocket 測試 WebSocket
PieSocket 必須
註冊
取得api key
才能使用,並設定notify_self
為1
才能回傳所送出的訊息
Line 28
this.connection.onopen = () => {
console.warn('connected to websocket server')
}
- 當 WebSocket object 建立成功後,會發起
open
event,可在此確定 WebSocket 是否建立成功
Line 23
this.connection.onmessage = msg => {
console.warn('receive message', msg)
this.message = msg.data
}
- WebSocket 所回傳訊息會觸發
message
event,可在此接受 WebSocket 所回傳訊息
Line 33
onSendMessage() {
let msg = 'Hello World'
console.warn('send message', msg)
this.connection.send(msg)
}
- 可透過 WebSocket object 的
send()
送出訊息給 WebSocket
Conclusion
- WebSocket 為 Web API 內建 class,可在 Vue 直接使用