import getWsUrl from './getWsUrl'; export default function (url) { const wsUri = getWsUrl(url); // 重连时间间隔 默认10秒 const reConnectDelay = 10 * 1000; return { data() { return { SOCKET: null, reConnectDelay, timer: null } }, computed: { isWSOpen () { return !!(this.SOCKET && 1 == this.SOCKET.readyState); } }, methods: { // 打开链接 openSocket() { // 初始化WebSocket this.WSClose(); this.WSInit(); }, // 初始化 WSInit() { // 未被初始化初始化 if (!this.isWSOpen) { console.log('=====WSinit, url:', wsUri); this.SOCKET = new WebSocket(wsUri); this.SOCKET.onmessage = this.onWSMessage; this.SOCKET.onopen = this.onWSOpen; this.SOCKET.onerror = this.onWSError; this.SOCKET.onclose = this.WSClose; } }, onWSOpen() { }, onWSMessage() { }, onWSError(Event) { console.log('链接失败', wsUri); this.WSClose(Event); }, WSClose(Event) { if (this.isWSOpen) { console.log('链接关闭', wsUri, Event); this.SOCKET.close(); this.SOCKET = null; // 没有event对象 则为手动关闭 if (Event) { this.reConnect(); } } }, // 重连 reConnect () { // 重连计时开始 就不另重连 if (this.timer) { return; } this.timer = setTimeout(() => { this.timer = null; this.WSInit(); }, this.reConnectDelay); } }, mounted () { this.openSocket(); }, beforeDestroy() { this.WSClose(); } } }