Vue 는 WebSocket 설정 을 통 해 단체 채 팅 기능 을 실현 합 니 다.

링크
JQuery 프로젝트 를 작성 할 때 웹 소켓 을 사용 하 는 것 은 간단 합 니 다.모듈 화,구성 요소 간 의 방문 문 제 를 고려 하지 않 고 문 서 를 대상 으로 프로 그래 밍 하면 됩 니 다.Vue 프로젝트 에서 사용 할 때 생각 보다 간단 하지 않 고 많은 장면 을 고려 해 야 합 니 다.이 글 은 개발 자 여러분 과 vue-native-websocket 라 이브 러 리 의 사용 과 설정 을 공유 하여 단체 채 팅 기능 을 실현 할 것 입 니 다.최종 실현 효 과 를 먼저 살 펴 보 겠 습 니 다.
 
설치 의존
본 고 는 vue-native-websocket 라 이브 러 리 에 대한 설명 입 니 다.프로젝트 에 vuex 가 설정 되 어 있 습 니 다.모 르 는 개발 자 는 공식 문 서 를 옮 기 십시오.이 글 을 계속 읽 는 것 을 선택 하면 힘 들 것 입 니 다.

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

설치 성공
플러그 인 설정
main.js 에서 가 져 오기import VueNativeSock from 'vue-native-websocket'VueNativeSock 플러그 인 을 사용 하고 관련 설정 을 진행 합 니 다.

// main.js
// base.lkWebSocket     websocket  
Vue.use(VueNativeSock,base.lkWebSocket,{
 //   Vuex  ,store     vuex
 store: store,
 //     /      json  
 format: "json",
 //       
 reconnection: true,
 //        
 reconnectionAttempts: 5,
 //       
 reconnectionDelay: 3000,
 //         ,     json               
 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 관련 설정:mutations 와 actions 관련 함수 추가

// vuex    
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

export default new Vuex.Store({
 state: {
 token:"",
 userID:"",
 //     
 profilePicture: "",
 socket: {
 //     
 isConnected: false,
 //     
 message: '',
 //       
 reconnectError: false
 }
 },
 mutations: {
 SOCKET_ONOPEN (state, event) {
 //          
 Vue.prototype.$socket = event.currentTarget;
 state.socket.isConnected = true
 },
 SOCKET_ONCLOSE (state, event) {
 //          
 state.socket.isConnected = false;
 console.log(event);
 },
 SOCKET_ONERROR (state, event) {
 //            
 console.error(state, event)
 },
 SOCKET_ONMESSAGE (state, message) {
 //           
 state.socket.message = message
 },
 SOCKET_RECONNECT(state, count) {
 //          
 console.info(state, count)
 },
 SOCKET_RECONNECT_ERROR(state) {
 //            
 state.socket.reconnectError = true;
 },
 },
 actions: {
 customerAdded (context) {
 //        
 console.log('action received: customerAdded');
 console.log(context)
 }
 },
 modules: {
 }
})

이로써 vue-native-websocket 설정 이 끝 났 습 니 다.더 많은 설정 방법 을 알 고 싶 으 시 면 npm 창 고 를 이동 하 십시오.
플러그 인 사용 및 단체 채 팅 실현
메시지 전송 수신 구성 요소 에 onmessage 감청 추가(mounted 수명 주기 중)

//       
this.$options.sockets.onmessage = (res)=>{
 // res.data         
 const data = JSON.parse(res.data);
 // 200                 (                  )
 if(data.code===200){
 //       
 console.log(data.msg);
 }else{
 //           
 const msgObj = {
 msg: data.msg,
 avatarSrc: data.avatarSrc,
 userID: data.userID
 };
 //     :  msgArray    json
 if(lodash.isEmpty(localStorage.getItem("msgArray"))){
 this.renderPage([],msgObj,0);
 }else{
 this.renderPage(JSON.parse(localStorage.getItem("msgArray")),msgObj,0);
 }
 }
};

메시지 전송 실현

//       
sendMessage: function (event) {
 if (event.keyCode === 13) {
 //          div  
 event.preventDefault();
 let msgText = "";
 //             
 let allNodes = event.target.childNodes;
 for(let item of allNodes){
 //          img  
 if(item.nodeName==="IMG"){
 msgText += `/${item.alt}/`;
 }
 else{
 //   text    
 if(item.nodeValue!==null){
 msgText += item.nodeValue;
 }
 }
 }
 //     :     、   、           、  id
 this.$socket.sendObj({msg: msgText,code: 0,avatarSrc: this.$store.state.profilePicture,userID: this.$store.state.userID});
 //          
 event.target.innerHTML = "";
 }
}

페이지 렌 더 링 실현

//       
renderPage: function(msgArray,msgObj,status){
 if(status===1){
 //        ,                
 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{
 //             
 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);
 }
 }
}

메시지 분석 실현

//     
messageParsing: function(msgObj){
 //              
 let separateReg = /(\/[^/]+\/)/g;
 let msgText = msgObj.msgText;
 let finalMsgText = "";
 //               
 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  :    
 msgText = msgText.replace(new RegExp(`/${item}/`,'g'),imgTag);
 }
 }
 }
 finalMsgText = msgText;
 }else{
 finalMsgText = msgText;
 }
 msgObj.msgText = finalMsgText;
 //     
 this.senderMessageList.push(msgObj);
 //        
 this.$nextTick(function () {
 this.$refs.messagesContainer.scrollTop = this.$refs.messagesContainer.scrollHeight;
 });
}

DOM 구조
모든 메시지 의 userID 와 vuex 에 저 장 된 현재 사용자 의 userID 를 통 해 현재 메시지 가 상대방 에 게 보 내 는 지 여 부 를 판단 합 니 다.

<!--    -->
<div class="messages-panel" ref="messagesContainer">
 <div class="row-panel" v-for="item in senderMessageList" :key="item.msgId">
 <!--       -->
 <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>
 <!--    -->
 <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>
 <!--    -->
 <p v-html="item.msgText"/>
 </div>
 </div>
 </div>
</div>
총결산
위 와 같이 소 편 이 소개 해 드 린 Vue 는 WebSocket 설정 을 통 해 단체 채 팅 기능 을 구현 하고 있 습 니 다.도움 이 되 셨 으 면 좋 겠 습 니 다!

좋은 웹페이지 즐겨찾기