36 lines
1.2 KiB
JavaScript
36 lines
1.2 KiB
JavaScript
window.useWebSocket = function useWebSocket() {
|
|
const { ref, onUnmounted } = Vue;
|
|
|
|
const connected = ref(false);
|
|
const logs = ref([]);
|
|
const paused = ref(false);
|
|
let ws = null;
|
|
let reconnectTimer = null;
|
|
|
|
function connect() {
|
|
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
ws = new WebSocket(`${proto}//${location.host}/ws`);
|
|
|
|
ws.onopen = () => { connected.value = true; };
|
|
ws.onclose = () => {
|
|
connected.value = false;
|
|
reconnectTimer = setTimeout(connect, 3000);
|
|
};
|
|
ws.onmessage = (e) => {
|
|
// 使用新数组引用,确保依赖 logs 的 watch/computed 能稳定触发(用于自动滚动到底部)
|
|
const nextLogs = [...logs.value, e.data];
|
|
logs.value = nextLogs.length > 2000 ? nextLogs.slice(-1500) : nextLogs;
|
|
};
|
|
}
|
|
|
|
function clear() { logs.value = []; }
|
|
function togglePause() { paused.value = !paused.value; }
|
|
|
|
function destroy() {
|
|
if (reconnectTimer) clearTimeout(reconnectTimer);
|
|
if (ws) ws.close();
|
|
}
|
|
|
|
return { connected, logs, paused, connect, clear, togglePause, destroy };
|
|
};
|