Easily consume Server-Sent Events (SSE) in your Vue application.
npm install @laravel/stream-vue
Provide your stream URL and the hook will automatically update the message
with the concatenated response as messages are returned from your server:
<script setup lang="ts">
import { useEventStream } from "@laravel/stream-vue";
const { message } = useEventStream("/stream");
</script>
<template>
<div>{{ message }}</div>
</template>
You also have access to the array of message parts:
<script setup lang="ts">
import { useEventStream } from "@laravel/stream-vue";
const { messageParts } = useEventStream("/stream");
</script>
<template>
<ul>
<li v-for="message in messageParts">
{{ message }}
</li>
</ul>
</template>
The second parameter is an options object where all properties are optional (defaults are shown below):
<script setup lang="ts">
import { useEventStream } from "@laravel/stream-vue";
const { message } = useEventStream("/stream", {
event: "update",
onMessage: (message) => {
//
},
onError: (error) => {
//
},
onComplete: () => {
//
},
endSignal: "</stream>",
glue: " ",
});
</script>
You can close the connection manually by using the returned close
function:
<script setup lang="ts">
import { useEventStream } from "@laravel/stream-vue";
import { onMounted } from "vue";
const { message, close } = useEventStream("/stream");
onMounted(() => {
setTimeout(() => {
close();
}, 3000);
});
</script>
<template>
<div>{{ message }}</div>
</template>
The clearMessage
function may be used to clear the message content that has been received so far:
<script setup lang="ts">
import { useEventStream } from "@laravel/stream-vue";
import { onMounted } from "vue";
const { message, clearMessage } = useEventStream("/stream");
onMounted(() => {
setTimeout(() => {
clearMessage();
}, 3000);
});
</script>
<template>
<div>{{ message }}</div>
</template>
Laravel Stream is open-sourced software licensed under the MIT license.