PrefaceThis article mainly uses websocked to establish a long connection, uses the global communication characteristics of Vuex, and the watch and computed functions to monitor message changes and drive page changes to achieve real-time chat. 1. The effect is as shown in the figure2. Specific implementation steps1. Introducing VuexThe code is as follows (example): //Install vuex npm install vuex //Introduce in main.js import store from './store' new Vue({ el: '#app', router, store, render: h => h(App) }) I have made a simple encapsulation of Vuex, as shown in the figure below. You can proceed according to your own habits. 2.webscoked implementationThe webscoked implementation is mainly divided into the following parts: Establishing a connection Sending heartbeat packets Reconnect after failure or error const state = { url: '', webSocket: null, lockReconnect: false, messageList: [], msgItem: {}, pingInterval: null, timeOut: null, } const mutations = { [types.INIT_WEBSOCKET](state, data) { state.webSocket = data }, [types.LOCK_RE_CONNECT](state, data) { state.lockReconnect = data }, [types.SET_PING_INTERVAL](state, data) { state.pingInterval = data }, [types.SET_MSG_LIST](state, data) { state.messageList.push(data) state.msgItem = data }, } const actions = { initWebSocket({ state, commit, dispatch, rootState }) { if (state.webSocket) { return } const realUrl = WSS_URL + rootState.doctorBasicInfo.token const webSocket = new WebSocket(realUrl) webSocket.onopen = () => { console.log('Establish link'); dispatch('heartCheck') } webSocket.onmessage = e => { console.log('Received message', e); try { if (typeof e.data === 'string' && e.data !== 'PONG') { let res = JSON.parse(e.data) console.log('Received content', res); commit('SET_MSG_LIST', res) } } catch (error) {} } webSocket.onclose = () => { console.log('close'); dispatch('reConnect') } webSocket.onerror = () => { console.log('failed'); dispatch('reConnect') } commit('INIT_WEBSOCKET', webSocket) }, // Heartbeat packet heartCheck({ state, commit }) { console.log(state, 'state'); const { webSocket } = state const pingInterval = setInterval(() => { if (webSocket.readyState === 1) { webSocket.send('PING') } }, 20000) commit('SET_PING_INTERVAL', pingInterval) }, //Reconnect reConnect({ state, commit, dispatch }) { if (state.lockReconnect) { return } commit('INIT_WEBSOCKET', null) commit('LOCK_RE_CONNECT', true) setTimeout(() => { dispatch('initWebSocket') commit('LOCK_RE_CONNECT', false) }, 20000) }, } const getters = { webSocket: state => state.webSocket, messageList: state => state.messageList, msgItem: state => state.msgItem, } export default { namespaced: true, state, actions, mutations, getters } Page Fetch methods: { ...mapActions("webSocket", ["initWebSocket", "close"]), pushItem(item) { const initMsg = item; this.msgList.push(initMsg); } } mounted() { this.initWebSocket(); } watch: msgItem: function (item) { this.pushItem(item); } }, computed: { ...mapGetters("webSocket", ["messageList", "msgItem"]), }, UI <li v-for="(item, i) in msgList" :key="i" class="msgBox"></li> Explanation of webscoked implementation ideas 1. First create a ws link in actions. 2. Use the watch attribute to monitor the corresponding message changes in the state on the page. When a new message is received, change the message list displayed on the page and use two-way binding to achieve automatic page updates. 3. When sending a message, call the backend interface and insert the new message into the message list displayed on the page 4. Because ws is a long link that will not be easily disconnected once established, as long as the message pushed by the backend is received and it is determined whether there is message content, when there is message content, you only need to change the message list in the state, and the page will be automatically updated according to the watch attribute, perfectly realizing the instant messaging function. SummarizeThis is the end of this article about implementing a real-time chat software with websocket+Vuex. For more relevant websocket+Vuex real-time chat content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: How to use the Linux basename command
>>: Causes and solutions for slow MySQL query speed and poor performance
Achieve results Implementation ideas The melting ...
Application example website http://www.uhuigou.net...
Introduction to kubectl kubectl is a command line...
Table of contents ReactRouterV6 Changes 1. <Sw...
Table of contents 1. Environment Introduction 2. ...
Table of contents 1. Introduction 1. What is an i...
Since the introduction of the contentEditable attr...
How to add css in html? There are three ways to s...
I have read an article written by the Yahoo team ...
1. Purpose Write a Flask application locally, pac...
Table of contents 1. Use object to create an obje...
The following is my judgment based on the data st...
This article example shares the specific code of ...
This article shares the specific code of Vue2.0 t...
1. Introduction to Nginx Nginx is a web server th...