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);
Usage
VueSSE can be invoked globally from the Vue object via Vue.SSE(...)
or from within components via this.$sse(...)
All of the following are valid calls to instantiate a connection to a event stream server:
Vue.SSE('/your-events-endpoint')
from anywhere the global Vue object is accessible;this.$sse('/your-events-endpoint')
from inside any component method/lifecycle hook;Vue.SSE('/your-events-endpoint', { format: 'json' })
will automatically process incoming messages as JSON;this.$sse('/your-events-endpoint', { withCredentials: true })
will set CORS on the request.
Configuration
Currently, VueSSE accepts the following config options
Command | 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" |
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 |
---|
getSource() | Returns the underlying EventSource. |
onError(function handler) | Allows your application to handle any errors thrown, such as loss of server connection and format pre-processing errors. |
subscribe(string event, function handler) | 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. |
unsubscribe(string event) | Removes all event-specific listeners from the event stream. |
close() | Closes the connection. Once closed, it cannot be re-opened!You will need to call $sse again. |
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>