This article mainly introduces how to implement a basic chat. In the future, we will add emoticons, photo upload and other functions. In fact, when I first came into contact with it, my biggest doubt was whether I needed to build some framework or download something in the early stage of the chat function. As a result, websocket can be used directly, and the front-end and back-end can be matched, and it is also free. I haven’t found any paid functions yet. Implementation effect diagram: First, encapsulate a websocket.js file (you can copy it directly, and then change the format of receiving/sending data to your own) import store from '@/store' var webSocket = null; var globalCallback = null; //Define the callback function for external data reception //Initialize websocket export function initWebSocket (url) { // Determine whether the browser supports websocket if ("WebSocket" in window) { webSocket = new WebSocket(url); //Create a socket object } else { alert("This browser does not support websocket!"); } //Open webSocket.onopen = function () { webSocketOpen(); }; //Receive mailwebSocket.onmessage = function (msg) { webSocketOnMessage(msg); }; //Close webSocket.onclose = function () { webSocketClose(); }; //Callback method when connection error occurs webSocket.onerror = function () { console.log("WebSocket connection error"); }; } //Trigger when the connection socket is established export function webSocketOpen () { console.log("WebSocket connection successful"); } //Triggered when the client receives data from the server, e is the received data object export function webSocketOnMessage (e) { // Store in the store, and then monitor the changes in the chat interface to automatically retrieve the received information store.commit('user/SET_WS_MSG', e) } //Send data export function webSocketSend (data) { console.log('send data'); //Convert the data format according to your needs here webSocket.send(JSON.stringify(data)); } //Close the socket export function webSocketClose () { webSocket.close() console.log("The conversation connection has been closed"); // } } //A function called in other places where a socket is needed to send and receive data export function sendSock (agentData, callback) { globalCallback = callback; //This callback is the function for receiving socket data defined when called elsewhere, which is very important. //The following judgment is mainly based on the possibility of socket connection interruption or other factors, so the message can be resent. switch (webSocket.readyState) { //CONNECTING: The value is 0, indicating that it is connecting. case webSocket.CONNECTING: setTimeout(function () { console.log('Connecting...'); webSocketSend(agentData, callback); }, 1000); break; //OPEN: The value is 1, indicating that the connection is successful and communication is possible. case webSocket.OPEN: console.log('Connection successful'); webSocketSend(agentData); break; //CLOSING: The value is 2, indicating that the connection is closing. case webSocket.CLOSING: setTimeout(function () { console.log('Connection closing'); webSocketSend(agentData, callback); }, 1000); break; //CLOSED: The value is 3, indicating that the connection has been closed or the connection opening failed. case webSocket.CLOSED: console.log('Connection closed/open failed'); // do something break; default: // this never happens break; } } //Export the socket initialization function, the data sending (receiving) function, and the connection closing function export default { initWebSocket, webSocketClose, sendSock }; Define the data received under storage in vuex store/modules/user.js let state = { webSocketMsg: '' }; //Modify state const mutations = { //Store messages pushed by websocket SET_WS_MSG: (state, msg) => { state.webSocketMsg = msg } } //Submit mutations. If you have problems with the accept block, you can add this to see //const actions = { // webSockets ({ commit }) { // commit('SET_WS_MSG', 2) // } //} store/getters.js //Get the state of state const getters = { webSocketMsg: state => state.user.webSocketMsg } export default getters Then start using websocket.vue in the chat interface <script> import { initWebSocket, sendSock, webSocketClose } from '@/utils/websocket.js' export default { data() { return { // This address is given by the backend and is used to connect to the websocket. Encrypted wss Unencrypted ws wsUrl:'ws://address', } }, // Get the received information from the store computed: { getSocketMsg() { return this.$store.state.user.webSocketMsg }, }, //Monitor getSocketMsg to see if it has received data watch: { getSocketMsg: { handler: function (val) { this.getConfigResult(val) }, }, //This step is the CSS design of my chat box. You don’t need to write it. You can refer to it when needed. // I store the received and sent messages in obList, and then monitor the value changes to keep the chat position at the bottom (overflow: auto; in css) obList: { handler: function (val) { this.$nextTick(() => { this.$refs.chatContent.scrollTop = this.$refs.chatContent.scrollHeight }) }, }, immediate: true, }, methods: { // Click the button to establish a chat connection customerDialog() { initWebSocket(this.wsUrl) }, // The method for receiving the socket callback function to return data. This function is called when I monitor the received data (in the watch above) getConfigResult(val) { }, // Click the send button to send the message---the format of the message to be sent needs to be confirmed with the backend sending() { sendSock('sent message') }, // Handle the chat box closing event handleClose() { //Close the connection webSocketClose() }, }, } </script> The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM. You may also be interested in:
|
<<: Several ways to submit HTML forms_PowerNode Java Academy
>>: Solve the splicing problem of deleting conditions in myBatis
The difference between http and https is For some...
Table of contents Preface Problem: Large file cop...
mistake The following error occurs when connectin...
1. Create an empty directory $ cd /home/xm6f/dev ...
1. Download, install and activate CLion Just foll...
Table of contents Overview 1. Dependency Injectio...
Some time ago, I needed to use pip downloads freq...
First look at the effect diagram: The complete co...
Table of contents Installation-free version of My...
First, let's simulate the data coming from th...
MouseEvent When the mouse performs a certain oper...
To beautify the table, you can set different bord...
The sudo command allows a trusted user to run a p...
Vue data two-way binding principle, but this meth...