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

How to export mysql table structure to excel

The requirements are as follows Export the table ...

MySQL chooses the right storage engine

When it comes to databases, one of the most frequ...

Summary of fragmented knowledge of Docker management

Table of contents 1. Overview 2. Application Exam...

Example of how to set up a third-level domain name in nginx

Problem Description By configuring nginx, you can...

Vue defines private filters and basic usage

The methods and concepts of private filters and g...

Vue implements a shopping cart that can change the shopping quantity

This article shares with you how to use Vue to ch...

How to skip errors in mysql master-slave replication

1. Traditional binlog master-slave replication, s...

Java+Tomcat environment deployment and installation process diagram

Next, I will install Java+Tomcat on Centos7. Ther...

How to modify the length limit of group_concat in Mysql

In MySQL, there is a function called "group_...

Basic syntax of MySQL index

An index is a sorted data structure! The fields t...

Detailed Tutorial on Installing MySQL 5.7 on RedHat 6.5

RedHat6.5 installation MySQL5.7 tutorial sharing,...