Create a real-time notification system using Vue and WebSocket
In modern application development, real-time has become an important part of the user experience. Especially in scenarios where real-time interaction is required, such as chat applications, online collaboration or notification systems, using WebSocket can greatly improve the user experience. As a popular front-end framework, Vue can easily build a real-time notification system with WebSocket. In this article, we will create a real-time notification system using Vue 3's Composition API (setup syntax sugar) with a simple example.
1. Project preparation
First, make sure that the Vue CLI is installed in your development environment. You can install it through the following command:
npm install -g @vue/cli
Create a new Vue project:
vue create realtime-notification-system
Enter the project directory:
cd realtime-notification-system
Next, install-client
Library for interacting with WebSocket:
npm install -client
2. Create a WebSocket Server
In our example we will use andLibrary to create a WebSocket server. First make sure you have installed , and then create a new folder as the server's workspace:
mkdir websocket-server cd websocket-server npm init -y npm install express
Then create a name calledThe file, the code is as follows:
const express = require('express'); const http = require('http'); const socketIo = require(''); const app = express(); const server = (app); const io = socketIo(server); ('/', (req, res) => { ('WebSocket server is running'); }); ('connection', (socket) => { ('A user connected'); // Send real-time notifications setInterval(() => { const notification = { message: 'New notification at ' + new Date().toLocaleTimeString(), id: ().toString(36).substr(2, 9) }; ('notification', notification); }, 5000); // Send notifications every 5 seconds ('disconnect', () => { ('A user disconnected'); }); }); const PORT = || 3000; (PORT, () => { (`Server is running on http://localhost:${PORT}`); });
Start the WebSocket server on the command line:
node
After the server starts, you should be able tohttp://localhost:3000
See the message that the WebSocket server is running.
3. Create a Vue app
In the Vue project, we need to connect to the WebSocket server and receive notifications. existsrc
In the directory, editThe file is as follows:
<template> <div > <h1>Real-time notification system</h1> <div v-if=" === 0">No new notification</div> <ul> <li v-for="notification in notifications" :key=""> {{ }} </li> </ul> </div> </template> <script> import { ref, onMounted, onBeforeUnmount } from 'vue'; import { io } from '-client'; export default { setup() { const notifications = ref([]); const socket = io('http://localhost:3000'); // Connect to WebSocket server onMounted(() => { // Listen to 'notification' events ('notification', (notification) => { (notification); }); }); onBeforeUnmount(() => { (); // Disconnect when component is destroyed }); return { notifications, }; }, }; </script> <style> #app { text-align: center; padding: 20px; } ul { list-style-type: none; padding: 0; } li { padding: 10px; background: #f0f0f0; margin-bottom: 10px; border-radius: 5px; } </style>
In the above code, we use ref to create a responsive notifications array to store notifications received in real time. When the component is mounted, we connect to the WebSocket server through the client and listen for notification events. Once a notification is received, it is added to the notifications array. When the component is destroyed, we disconnect from the WebSocket server to avoid memory leaks.
4. Run the Vue app
Next, we launch the Vue application in the Vue project directory:
npm run serve
You can access it in the browserhttp://localhost:8080
, view the effect of real-time notification system. Every 5 seconds, you will see new notifications appear automatically on the page.
5. Summary
By creating a real-time notification system using Vue 3 and WebSocket, we are able to provide users with instant updates of information. You can further expand this system according to business needs, such as implementing notification classification, priority management, user online status management, etc. Real-time systems can not only improve user experience, but also effectively enhance user participation.
In this article, we describe how to use Vue's Composition API and quickly implement a real-time notification system. Hopefully this example will inspire you to build more complex real-time interaction features. In the future, you may also encounter more complex needs such as data persistence and user authentication. It is recommended to use Vuex for global state management to further strengthen the expansion and maintainability of the system.
The above is the detailed content of using Vue and WebSocket to create a real-time notification system. For more information about Vue WebSocket real-time notification system, please follow my other related articles!