组件化 websocket
实时数据响应,组件化websocket减少代码冗余
组件定义 websocket.vue
<template><div></div>
</template><script>export default {data() {return {webSocket: null, // webSocket实例lockReconnect: false, // 重连锁,避免多次重连maxReconnect: 3, // 最大重连次数, -1 标识无限重连reconnectTime: 0, // 重连尝试次数};},created() {this.initWebSocket()},destroyed: function () {this.webSocket.close()},//方法集合methods: {/*** 初始化 weoSocket*/initWebSocket() {// ws地址 const host = 'XXXXXXX'const wsUri = `ws://${host}:3000`console.log(wsUri)// 建立连接this.webSocket = new WebSocket(wsUri)// 连接成功this.webSocket.onopen = this.onOpen// 连接错误this.webSocket.onerror = this.onError// 接收信息this.webSocket.onmessage = this.onMessage// 连接关闭this.webSocket.onclose = this.onClose},/*** 连接成功事件*/onOpen() {console.log('WebSocket connection success')this.reconnectTime = 0},/*** 数据发送* @param msg*/send(msg) {//数据发送this.webSocket.send(msg)console.log('Websocket send:',msg)},/*** 连接失败事件* @param e*/onError(e) {//错误console.log(`WebSocket connection error:${e.code} ${e.reason} ${e.wasClean}`)//重连// this.reconnect()},/*** 连接关闭事件* @param e*/onClose(e) {//关闭console.log(`WebSocket connection closed:${e.code} ${e.reason} ${e.wasClean}`)//重连// this.reconnect()},/*** 重新连接*/reconnect() {if (this.lockReconnect || (this.maxReconnect !== -1 && this.reconnectTime > this.maxReconnect)) {return}this.lockReconnect = truesetTimeout(() => {this.reconnectTime++// 建立新连接this.initWebSocket()this.lockReconnect = false}, 5000)},/*** 接收服务器推送的信息* @param msgEvent*/onMessage(msgEvent) {// console.log('日志信息打印:',msgEvent)this.$emit('onMessage', msgEvent.data)},},}
</script>
组件引用
<myWebsocket v-if="dialogVisible" @onMessage="getMsg" />