By using this composable you can access the global object provided by the plugin and call any method to work with sockets on your backend.
components/Broadcast.client.vue
<script setup lang="ts">
const echo = useEcho()
const messages = ref<string[]>([])
const writeNewMessage = (e: object) => messages.value.push(JSON.stringify(e))
function stopAllListeners() {
echo.leaveAllChannels()
}
function subscribeToPublicChannel() {
const name = 'public'
const event = '.PublicEvent'
echo
.channel(name)
.listen(event, (e: object) => writeNewMessage(e))
.error((e: object) => {
console.error('Public channel error', e)
})
}
function subscribeToPrivateChannel() {
const name = 'users'
const event = '.PrivateEvent'
echo
.private(name)
.listen(event, (e: object) => writeNewMessage(e))
.error((e: object) => {
console.error('Private channel error', e)
})
}
onMounted(() => {
subscribeToPublicChannel();
subscribeToPrivateChannel();
})
</script>
Keep in mind, for accessing Private and Presence channels you should have configured authentication on your backend side, preferably Laravel Sanctum.