Usage
Topics
Automatic topic subscriptions and reactive shared state management.
Both useWS
for the client and defineWSHandler
for the server handle automatic topic subscriptions. This means that when a connection is established, the client will automatically subscribe to the topics defined in the runtime configuration. The server can then publish messages to these topics, and the client will receive them.
useWS
also accept the topic parameter as a reactive array. This allows to automatically and dynamically subscribe and unsubscribe to topics after the connection is established.
Example
<template>
<div>
<div>
<ul>
<li v-for="topic in availableTopics" :key="topic">
<label>
<input type="checkbox" v-model="topics" :value="topic" />
{{ topic }}
</label>
</li>
</ul>
</div>
<div v-if="states['chat']">
<div v-for="(message, key) in states['chat']" :key>
<strong>{{ message.user }}</strong>: {{ message.text }}
</div>
</div>
<div v-if="states['notifications']">
{{ notification.message }}
</div>
</div>
</template>
<script setup lang="ts">
const availableTopics = ref(['chat', 'notifications'])
const topics = ref(['chat'])
const { states, send } = useWS<{
chat?: {
user?: string,
text: string,
}[],
notifications?: {
message: string,
},
}>(topics)
</script>
Make sure to type any dynamic topic as optional, as they might not be available.