A type-safe Vue composable for seamless SignalR hub integration with automatic connection management and reactive event handling.
- Vue 3
- TypeScript
- SignalR
Install the required dependencies:
bun add @microsoft/signalr vue
bun add -D @types/signalr
The useSignalR
composable provides the following reactive properties and methods:
connection
: Current SignalR connection instanceisConnected
: Reactive boolean indicating connection statusconnectionError
: Reactive error object for connection issuesevents
: Reactive storage of received events
connect()
: Manually establish SignalR connectiondisconnect()
: Manually close SignalR connectionon(eventName, callback)
: Listen to specific server eventsinvoke(methodName, ...args)
: Invoke server methods
<script setup lang="ts">
import { ref } from 'vue'
import { useSignalR } from '@/composables/useSignalR'
// Define data interface
interface Message {
user: string
text: string
timestamp: Date
}
// Create SignalR connection
const {
isConnected,
connectionError,
on,
invoke
} = useSignalR<Message>('https://your-signalr-hub-url')
// Reactive messages list
const messages = ref<Message[]>([])
const newMessage = ref('')
// Listen for incoming messages
on('ReceiveMessage', (message: Message) => {
messages.value.push(message)
})
// Send a message
async function sendMessage() {
if (isConnected.value && newMessage.value.trim()) {
await invoke('SendMessage', {
user: 'CurrentUser',
text: newMessage.value,
timestamp: new Date()
})
newMessage.value = '' // Clear input after sending
}
}
</script>
const { connect, disconnect, isConnected } = useSignalR('https://your-hub-url');
// Manually control connection
function toggleConnection() {
if (isConnected.value) {
disconnect();
} else {
connect();
}
}
// Listen to multiple events
on('Event1', (data) => {
// Handle Event1
});
on('Event2', (data) => {
// Handle Event2
});
- Supports generic typing for type-safe event handling
- Automatic connection on component mount
- Automatic disconnection on component unmount
- Built-in error handling
const { connectionError } = useSignalR('https://your-hub-url');
// Check and handle connection errors
if (connectionError.value) {
console.error('Connection failed:', connectionError.value.message);
}
- Ensure your SignalR hub URL is correct
- Handle authentication if required by your hub
- Consider network and connection stability
Fully typed with generics for flexible and type-safe usage.