Vue中使用websocket(开箱即用)

tech2023-02-03  94

<template> <div class="test"> </div> </template> <script> export default { name: 'test', data() { return { websocket: null, } }, created() { // 初始化 this.initWebSocket() }, destroyed() { // 关闭链接 this.websocket.close() }, methods: { initWebSocket() { const uri = 'ws://127.0.0.1:5000/ws/message' this.websocket = new WebSocket(uri) this.websocket.onmessage = this.websocketOnMessage this.websocket.onopen = this.websocketOnOpen this.websocket.onerror = this.websocketOnError this.websocket.onclose = this.websocketClose }, websocketOnOpen() { console.log('建立连接') }, websocketOnError() { // 连接建立失败重连 this.initWebSocket() }, websocketOnMessage(e) { // 数据接收 console.log(e.data) this.percent = Number(e.data) }, websocketSend(data) { // 数据发送 this.websocket.send(data) }, websocketClose(e) { // 关闭 console.log('断开连接', e) }, }, } </script> <style> </style>
最新回复(0)