怎么在Vue中通過配置WebSocket實(shí)現(xiàn)群聊功能-創(chuàng)新互聯(lián)

怎么在Vue中通過配置WebSocket實(shí)現(xiàn)群聊功能?針對這個(gè)問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。

站在用戶的角度思考問題,與客戶深入溝通,找到贛州網(wǎng)站設(shè)計(jì)與贛州網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗(yàn),讓設(shè)計(jì)與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個(gè)性化、用戶體驗(yàn)好的作品,建站類型包括:網(wǎng)站設(shè)計(jì)制作、成都網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣、國際域名空間、網(wǎng)絡(luò)空間、企業(yè)郵箱。業(yè)務(wù)覆蓋贛州地區(qū)。

安裝依賴

vue-native-websocket安裝
# yarn | npm 安裝
yarn add vue-native-websocket | npm install vue-native-websocket --save

怎么在Vue中通過配置WebSocket實(shí)現(xiàn)群聊功能

安裝成功

配置插件

在 main.js 中進(jìn)行導(dǎo)入

import VueNativeSock from 'vue-native-websocket'

使用 VueNativeSock 插件,并進(jìn)行相關(guān)配置

// main.js
// base.lkWebSocket為你服務(wù)端websocket地址
Vue.use(VueNativeSock,base.lkWebSocket,{
 // 啟用Vuex集成,store的值為你的vuex
 store: store,
 // 數(shù)據(jù)發(fā)送/接收使用使用json格式
 format: "json",
 // 開啟自動(dòng)重連
 reconnection: true,
 // 嘗試重連的次數(shù)
 reconnectionAttempts: 5,
 // 重連間隔時(shí)間
 reconnectionDelay: 3000,
 // 將數(shù)據(jù)進(jìn)行序列化,由于啟用了json格式的數(shù)據(jù)傳輸這里需要進(jìn)行重寫
 passToStoreHandler: function (eventName, event) {
 if (!eventName.startsWith('SOCKET_')) { return }
 let method = 'commit';
 let target = eventName.toUpperCase();
 let msg = event;
 if (this.format === 'json' && event.data) {
 msg = JSON.parse(event.data);
 if (msg.mutation) {
 target = [msg.namespace || '', msg.mutation].filter((e) => !!e).join('/');
 } else if (msg.action) {
 method = 'dispatch';
 target = [msg.namespace || '', msg.action].filter((e) => !!e).join('/');
 }
 }
 this.store[method](target, msg);
 this.store.state.socket.message = msg;
 }
});

vuex的相關(guān)配置:mutations和actions添加相關(guān)函數(shù)

// vuex配置文件
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

export default new Vuex.Store({
 state: {
 token:"",
 userID:"",
 // 用戶頭像
 profilePicture: "",
 socket: {
 // 連接狀態(tài)
 isConnected: false,
 // 消息內(nèi)容
 message: '',
 // 重新連接錯(cuò)誤
 reconnectError: false
 }
 },
 mutations: {
 SOCKET_ONOPEN (state, event) {
 // 連接打開觸發(fā)的函數(shù)
 Vue.prototype.$socket = event.currentTarget;
 state.socket.isConnected = true
 },
 SOCKET_ONCLOSE (state, event) {
 // 連接關(guān)閉觸發(fā)的函數(shù)
 state.socket.isConnected = false;
 console.log(event);
 },
 SOCKET_ONERROR (state, event) {
 // 連接發(fā)生錯(cuò)誤觸發(fā)的函數(shù)
 console.error(state, event)
 },
 SOCKET_ONMESSAGE (state, message) {
 // 收到消息時(shí)觸發(fā)的函數(shù)
 state.socket.message = message
 },
 SOCKET_RECONNECT(state, count) {
 // 重新連接觸發(fā)的函數(shù)
 console.info(state, count)
 },
 SOCKET_RECONNECT_ERROR(state) {
 // 重新連接失敗觸發(fā)的函數(shù)
 state.socket.reconnectError = true;
 },
 },
 actions: {
 customerAdded (context) {
 // 新連接添加函數(shù)
 console.log('action received: customerAdded');
 console.log(context)
 }
 },
 modules: {
 }
})

至此 vue-native-websocket 配置結(jié)束,如需了解更多配置方法,請移步 npm倉庫

使用插件并實(shí)現(xiàn)群聊

在消息發(fā)送接收組件中添加 onmessage 監(jiān)聽(mounted生命周期中)

// 監(jiān)聽消息接收
this.$options.sockets.onmessage = (res)=>{
 // res.data為服務(wù)端返回的數(shù)據(jù)
 const data = JSON.parse(res.data);
 // 200為服務(wù)端連接建立成功時(shí)返回的狀態(tài)碼(此處根據(jù)真實(shí)后端返回值進(jìn)行相應(yīng)的修改)
 if(data.code===200){
 // 連接建立成功
 console.log(data.msg);
 }else{
 // 獲取服務(wù)端推送的消息
 const msgObj = {
 msg: data.msg,
 avatarSrc: data.avatarSrc,
 userID: data.userID
 };
 // 渲染頁面:如果msgArray存在則轉(zhuǎn)json
 if(lodash.isEmpty(localStorage.getItem("msgArray"))){
 this.renderPage([],msgObj,0);
 }else{
 this.renderPage(JSON.parse(localStorage.getItem("msgArray")),msgObj,0);
 }
 }
};

實(shí)現(xiàn)消息發(fā)送

// 消息發(fā)送函數(shù)
sendMessage: function (event) {
 if (event.keyCode === 13) {
 // 阻止編輯框默認(rèn)生成div事件
 event.preventDefault();
 let msgText = "";
 // 獲取輸入框下的所有子元素
 let allNodes = event.target.childNodes;
 for(let item of allNodes){
 // 判斷當(dāng)前元素是否為img元素
 if(item.nodeName==="IMG"){
 msgText += `/${item.alt}/`;
 }
 else{
 // 獲取text節(jié)點(diǎn)的值
 if(item.nodeValue!==null){
 msgText += item.nodeValue;
 }
 }
 }
 // 消息發(fā)送: 消息內(nèi)容、狀態(tài)碼、當(dāng)前登錄用戶的頭像地址、用戶id
 this.$socket.sendObj({msg: msgText,code: 0,avatarSrc: this.$store.state.profilePicture,userID: this.$store.state.userID});
 // 清空輸入框中的內(nèi)容
 event.target.innerHTML = "";
 }
}

實(shí)現(xiàn)頁面渲染

// 渲染頁面函數(shù)
renderPage: function(msgArray,msgObj,status){
 if(status===1){
 // 頁面第一次加載,如果本地存儲(chǔ)中有數(shù)據(jù)則渲染至頁面
 let msgArray = [];
 if(localStorage.getItem("msgArray")!==null){
 msgArray = JSON.parse(localStorage.getItem("msgArray"));
 for (let i = 0; i<msgArray.length;i++){
 const thisSenderMessageObj = {
 "msgText": msgArray[i].msg,
 "msgId": i,
 "avatarSrc": msgArray[i].avatarSrc,
 "userID": msgArray[i].userID
 };
 // 解析并渲染
 this.messageParsing(thisSenderMessageObj);
 }
 }
 }else{
 // 判斷本地存儲(chǔ)中是否有數(shù)據(jù)
 if(localStorage.getItem("msgArray")===null){
 // 新增記錄
 msgArray.push(msgObj);
 localStorage.setItem("msgArray",JSON.stringify(msgArray));
 for (let i = 0; i <msgArray.length; i++){
 const thisSenderMessageObj = {
 "msgText": msgArray[i].msg,
 "msgId": i,
 "avatarSrc": msgArray[i].avatarSrc,
 "userID": msgArray[i].userID,
 };
 // 解析并渲染
 this.messageParsing(thisSenderMessageObj);
 }
 }else{
 // 更新記錄
 msgArray = JSON.parse(localStorage.getItem("msgArray"));
 msgArray.push(msgObj);
 localStorage.setItem("msgArray",JSON.stringify(msgArray));
 const thisSenderMessageObj = {
 "msgText": msgObj.msg,
 "msgId": Date.now(),
 "avatarSrc": msgObj.avatarSrc,
 "userID": msgObj.userID
 };
 // 解析并渲染
 this.messageParsing(thisSenderMessageObj);
 }
 }
}

實(shí)現(xiàn)消息解析

// 消息解析
messageParsing: function(msgObj){
 // 解析接口返回的數(shù)據(jù)進(jìn)行渲染
 let separateReg = /(\/[^/]+\/)/g;
 let msgText = msgObj.msgText;
 let finalMsgText = "";
 // 將符合條件的字符串放到數(shù)組里
 const resultArray = msgText.match(separateReg);
 if(resultArray!==null){
 for (let item of resultArray){
 // 刪除字符串中的/符號
 item = item.replace(/\//g,"");
 for (let emojiItem of this.emojiList){
 // 判斷捕獲到的字符串與配置文件中的字符串是否相同
 if(emojiItem.info === item){
 const imgSrc = require(`../assets/img/emoji/${emojiItem.hover}`);
 const imgTag = `<img src="${imgSrc}" width="28" height="28" alt="${item}">`;
 // 替換匹配的字符串為img標(biāo)簽:全局替換
 msgText = msgText.replace(new RegExp(`/${item}/`,'g'),imgTag);
 }
 }
 }
 finalMsgText = msgText;
 }else{
 finalMsgText = msgText;
 }
 msgObj.msgText = finalMsgText;
 // 渲染頁面
 this.senderMessageList.push(msgObj);
 // 修改滾動(dòng)條位置
 this.$nextTick(function () {
 this.$refs.messagesContainer.scrollTop = this.$refs.messagesContainer.scrollHeight;
 });
}

DOM結(jié)構(gòu)

通過每條消息的userID和vuex中的存儲(chǔ)的當(dāng)前用戶的userID來判斷當(dāng)前消息是否為對方發(fā)送

<!--消息顯示-->
<div class="messages-panel" ref="messagesContainer">
 <div class="row-panel" v-for="item in senderMessageList" :key="item.msgId">
 <!--發(fā)送者消息樣式-->
 <div class="sender-panel" v-if="item.userID===userID">
 <!--消息-->
 <div class="msg-body">
 <!--消息尾巴-->
 <div class="tail-panel">
 <svg class="icon" aria-hidden="true">
 <use xlink:href="#icon-zbds30duihuakuangyou" rel="external nofollow" ></use>
 </svg>
 </div>
 <!--消息內(nèi)容-->
 <p v-html="item.msgText"/>
 </div>
 <!--頭像-->
 <div class="avatar-panel">
 <img :src="item.avatarSrc" alt="">
 </div>
 </div>
 <!--對方消息樣式-->
 <div class="otherSide-panel" v-else>
 <!--頭像-->
 <div class="avatar-panel">
 <img :src="item.avatarSrc" alt="">
 </div>
 <!--消息-->
 <div class="msg-body">
 <!--消息尾巴-->
 <div class="tail-panel">
 <svg class="icon" aria-hidden="true">
 <use xlink:href="#icon-zbds30duihuakuangzuo" rel="external nofollow" ></use>
 </svg>
 </div>
 <!--消息內(nèi)容-->
 <p v-html="item.msgText"/>
 </div>
 </div>
 </div>
</div>

vue是什么

Vue是一套用于構(gòu)建用戶界面的漸進(jìn)式JavaScript框架,Vue與其它大型框架的區(qū)別是,使用Vue可以自底向上逐層應(yīng)用,其核心庫只關(guān)注視圖層,方便與第三方庫和項(xiàng)目整合,且使用Vue可以采用單文件組件和Vue生態(tài)系統(tǒng)支持的庫開發(fā)復(fù)雜的單頁應(yīng)用。

關(guān)于怎么在Vue中通過配置WebSocket實(shí)現(xiàn)群聊功能問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)成都網(wǎng)站設(shè)計(jì)公司行業(yè)資訊頻道了解更多相關(guān)知識。

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。

分享名稱:怎么在Vue中通過配置WebSocket實(shí)現(xiàn)群聊功能-創(chuàng)新互聯(lián)
URL鏈接:http://muchs.cn/article42/dphiec.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管網(wǎng)站導(dǎo)航、網(wǎng)站維護(hù)品牌網(wǎng)站建設(shè)、全網(wǎng)營銷推廣、網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都做網(wǎng)站