import { ref, onMounted, onUnmounted } from 'vue'; let socket; // Declare the WebSocket outside the function to maintain a single connection export function useWebSocket(url) { const message = ref(null); // Function to handle incoming WebSocket messages function handleMessage(event) { message.value = event.data; } // Function to handle WebSocket connection function connect() { socket = new WebSocket(url); socket.addEventListener('message', handleMessage); } // Function to handle WebSocket disconnection function disconnect() { if (socket) { socket.removeEventListener('message', handleMessage); socket.close(); } } // Connect WebSocket when the first component is mounted onMounted(() => { if (!socket || socket.readyState !== WebSocket.OPEN) { connect(); } }); // Disconnect WebSocket when the last component is unmounted onUnmounted(() => { if (socket && socket.readyState === WebSocket.OPEN) { disconnect(); } }); // Function to send data over WebSocket function sendMessage(data) { if (socket && socket.readyState === WebSocket.OPEN) { socket.send(data); } else { console.error('WebSocket connection is not open.'); } } // Return the necessary values and functions for components to use return { message, sendMessage }; }