VueSSE
VueSSE enables effortless use of Server-Sent Events by providing a high-level interface to an underlying EventSource.
Install
npm install --save vue-sse
yarn add vue-sse
import VueSSE from 'vue-sse';
Vue.use(VueSSE);
import VueSSE from 'vue-sse';
Vue.use(VueSSE, {
format: 'json',
polyfill: true,
url: 'http://my.api.com/sse'
withCredentials: true,
});
Usage
VueSSE can be invoked globally from the Vue object via Vue.$sse.create(...)
or from within components via this.$sse.create(...)
All of the following are valid calls to instantiate a connection to a event stream server:
Vue.$sse.create({ url: '/your-events-endpoint' })
from anywhere the global Vue object is accessible;this.$sse.create({ url: '/your-events-endpoint' })
from inside any component method/lifecycle hook;Vue.$sse.create({ url: '/your-events-endpoint', format: 'json' })
will automatically process incoming messages as JSON;this.$sse.create({ url: '/your-events-endpoint', withCredentials: true })
will set CORS on the request.
Configuration
VueSSE accepts the following config options when adding VueSSE via Vue.use(...)
and when calling $sse.create
.
Option | Description | Default |
---|
format: _ | Specify pre-processing, if any, to perform on incoming messages. Currently, only a JSON formatter is available by specifying "json" . Messages that fail formatting will emit an error. | "plain" |
polyfill | Include an EventSource polyfill for older browsers | false |
url | The location of the SSE server | "" |
withCredentials | Indicates if CORS should be set to include credentials. | false |
Methods
Once you've successfully connected to an events server, an object will be returned with the following methods:
Name | Description |
---|
connect(): Promise | |
source | Returns the underlying EventSource. |
onError(handler: function): SSEClient | Allows your application to handle any errors thrown, such as loss of server connection and format pre-processing errors. |
on(string event, function handler): SSEClient | Adds an event-specific listener to the event stream. The handler function receives the message as its argument (formatted if a format was specified), and the original underlying Event. |
once(string event, function handler): SSEClient | Same as on, but only triggered once. |
off(string event): SSEClient | Removes all event-specific listeners from the event stream. |
disconnect() | Closes the connection. |
Examples
Promises
<template>
<div>
<p v-for="message in messages">{{ message }}</p>
</div>
</template>
<script>
let msgServer;
export default {
name: 'sse-test',
data() {
return {
messages: [],
};
},
mounted() {
this.$sse('/your-events-server', { format: 'json' })
.then(sse => {
msgServer = sse;
sse.onError(e => {
console.error('lost connection; giving up!', e);
sse.close();
});
sse.subscribe('', (message, rawEvent) => {
console.warn('Received a message w/o an event!', message);
});
sse.subscribe('chat', (message, rawEvent) => {
this.messages.push(message);
});
setTimeout(() => {
sse.unsubscribe('');
console.log('Stopped listening to event-less messages!');
}, 7000);
setTimeout(() => {
sse.unsubscribe('chat');
console.log('Stopped listening to chat messages!');
}, 14000);
})
.catch(err => {
console.error('Failed to connect to server', err);
});
},
beforeDestroy() {
msgServer.close();
},
};
</script>
Async/Await
<template>
<div>
<p v-for="message in messages">{{ message }}</p>
</div>
</template>
<script>
let msgServer;
export default {
name: 'sse-test',
data() {
return {
messages: [],
};
},
mounted() {
(async () => {
try {
msgServer = await $sse('/your-events-server', { format: 'json' });
msgServer.onError(e => {
console.error('lost connection; giving up!', e);
});
msgServer.subscribe('', (data, rawEvent) => {
console.warn('Received a message w/o an event!', data);
});
msgServer.subscribe('chat', (message, rawEvent) => {
this.messages.push(message);
});
setTimeout(() => {
msgServer.unsubscribe('');
console.log('Stopped listening to event-less messages!');
}, 7000);
setTimeout(() => {
msgServer.unsubscribe('chat');
console.log('Stopped listening to chat messages');
}, 14000);
} catch (err) {
console.error('Failed to connect to server', err);
}
})();
},
beforeDestroy() {
msgServer.close();
},
};
</script>