Vue implements websocket customer service chat function

Vue implements websocket customer service chat function

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:
  • Vue+Websocket simply implements the chat function
  • Vue uses WebSocket to simulate the chat function
  • Websocket+Vuex implements a real-time chat software
  • Vue + WebSocket + WaveSurferJS to implement H5 chat dialogue interaction example
  • Implementing simple WebSocket chat function based on node+vue
  • Multi-person online chat room based on vue and websocket
  • Vue+web terminal imitates WeChat web version chat room function
  • Vue.js imitates WeChat chat window to display component functions
  • Vue + socket.io implements a simple chat room sample code

<<:  Several ways to submit HTML forms_PowerNode Java Academy

>>:  Solve the splicing problem of deleting conditions in myBatis

Recommend

Complete steps to upgrade Nginx http to https

The difference between http and https is For some...

How to write memory-efficient applications with Node.js

Table of contents Preface Problem: Large file cop...

Navicat connects to MySQL8.0.11 and an error 2059 occurs

mistake The following error occurs when connectin...

How to create your own image using Dockerfile

1. Create an empty directory $ cd /home/xm6f/dev ...

Angular Dependency Injection Explained

Table of contents Overview 1. Dependency Injectio...

How to use docker+devpi to build local pypi source

Some time ago, I needed to use pip downloads freq...

Sample code using the element calendar component in Vue

First look at the effect diagram: The complete co...

Detailed tutorial on MySQL installation and configuration

Table of contents Installation-free version of My...

Implementation of react loop data (list)

First, let's simulate the data coming from th...

JavaScript MouseEvent Case Study

MouseEvent When the mouse performs a certain oper...

HTML table markup tutorial (4): border color attribute BORDERCOLOR

To beautify the table, you can set different bord...

How to run sudo command without entering password in Linux

The sudo command allows a trusted user to run a p...

Analysis of the reasons why Vue3 uses Proxy to implement data monitoring

Vue data two-way binding principle, but this meth...