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
1. First log in to the Alibaba Cloud website to r...
Table of contents 1. Background 2. Local custom i...
Table of contents 1. Example: this can directly g...
Table of contents Written in front Environment de...
1. Download the installation package The installa...
MySQL is a relational database management system ...
Table of contents 1. Principle Overview Query Cac...
Table of contents Diffing Algorithm Layer-by-laye...
RPM package management A packaging and installati...
Preview address: https://ovsexia.gitee.io/leftfix...
Introduction to IPSec IPSec (Internet Protocol Se...
A very common scenario in react projects: const [...
Why are the SQL queries you write slow? Why do th...
1. Command method Run the nginx service in the cr...
Many people also asked me what books I read when ...