How to use WebSocket to implement chat function in Vue technology development
2.1 Install Vue
Use the following command to install Vue:
npm install vue
2.2 Install the WebSocket client library
Use the following command to install the WebSocket client library:
npm install vue-native-websocket
import Vue from 'vue' import VueNativeSock from 'vue-native-websocket' Vue.use(VueNativeSock, 'ws://localhost:3000', { connectManually: true, // 手动连接 reconnection: true, // 自动重连 reconnectionAttempts: 5, // 重连尝试次数 }) new Vue({ render: h => h(App), }).$mount('#app')
Here, we set the WebSocket connection address to 'ws://localhost:3000', you can modify it according to the actual situation.
<template> <div> <div v-for="message in messages" :key="message.id">{{ message.content }}</div> <input v-model="inputMessage"> <button @click="sendMessage">发送</button> </div> </template> <script> export default { data() { return { messages: [], inputMessage: '', } }, mounted() { this.$options.sockets.onmessage = (event) => { const message = JSON.parse(event.data) this.messages.push(message) } this.$options.sockets.connect() // 手动连接WebSocket }, methods: { sendMessage() { const message = { content: this.inputMessage, } this.$options.sockets.send(JSON.stringify(message)) this.inputMessage = '' }, }, } </script>
In the above code, we use the v-for directive to render each chat message to the interface, and bind the content of the input box through the v-model directive. When the send button is clicked, the sendMessage function is called to send the entered message to the server.
const WebSocket = require('ws') const wss = new WebSocket.Server({ port: 3000 }) wss.on('connection', (ws) => { ws.on('message', (message) => { wss.clients.forEach((client) => { client.send(message) }) }) })
In the above code, we listen to port 3000. When a client connects, the connection event will be triggered. When a message sent by a client is received, the message is broadcast to all connected clients.
npm run serve
Visit http://localhost:8080 in the browser to see the chat interface.
The above is the detailed content of How to use WebSocket to implement chat function in Vue technology development. For more information, please follow other related articles on the PHP Chinese website!