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.
Echo instance and available functions, check official Laravel Broadcasting documentation.Here is an example of a client component subscribing to the public and private channels:
<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>