How to use socketio client in vuejs3
Vuejs is progressive javascript framework which is used for building user interfaces. Learn more about it here
Socketio is a library that enables low-latency, bidirectional and event-based communication between a client and a server.
It is built on top of the WebSocket protocol and provides additional guarantees like a fallback to HTTP long-polling or automatic reconnection. Learn more about socket io here
Steps to implement socketio client in vuejs3
-
Install socket.io client
# Yarn
yarn install socket.io-client
#npm
npm install socket.io-client --save
-
This class return instance of the socketio Create class inside src/services/SocketioService.js
SocketioService.js
import {io} from 'socket.io-client';
class SocketioService {
socket;
constructor() { }
setupSocketConnection() {
this.socket = io(URL, {
transports: ["websocket"]
})
return this.socket;
}
}
export default new SocketioService();
-
Setup a socket Connection
import SocketioService and setupSocketConnection. In example I am listening to the welcome channel and notification events. I have use quasar notify to display notification message.
<script>
import { ref } from "vue";
import SocketioService from "./services/socketio.service.js";
export default {
name: "LayoutDefault",
data() {
return {
socket: null,
};
},
components: {},
mounted() {
const socket = SocketioService.setupSocketConnection();
socket.on("welcome", (data) => {
const res = JSON.parse(data);
if (res?.data == "Connected") {
this.$q.notify({
type: "positive",
message: `Welcome`,
classes: "glossy",
});
}
});
socket.on("notifications", (data) => {
const res = JSON.parse(data);
let type = res?.variant == "error" ? "negative" : "positive";
this.$q.notify({
type: type,
message: res?.message,
position: "bottom-right",
});
});
},
};
</script>