Vue.js(Nuxt.js)からwebsocketを扱う方法
Author: 水卜
Author: 水卜
npm install websocket
vueファイルに以下記述
import { w3cwebsocket } from 'websocket'
const W3CWebSocket = w3cwebsocket
export default {
data () {
return {
ws: new W3CWebSocket('ws://localhost:8080/pipe'),
devices: [
{
data: []
}
]
}
},
created () {
const self = this
self.ws.onmessage = (e) => {
if (typeof e.data === 'string') {
const res = JSON.parse(e.data)
self.devices[0].data.push({ createdAt: new Date(res.time).toLocaleString(), value: res.message })
}
}
},
methods: {
publish (i) {
this.ws.send(JSON.stringify({ message: 'hello' }))
}
}
}