本文章主要介绍如何实现一个基本的聊天,后续会添加表情包,传照片等功能
其实刚开始接触的时候,我最大的疑惑是聊天功能的前期是否需要搭建什么框架,下载一些什么之类的,结果就是其实websocket可以直接使用,然后前后端搭配,也是免费的,暂时没发现需要收费功能的东西~
实现效果图~
首先封装一个websocket.js文件(大家可以直接复制,然后把接收数据之类的格式改成自己的就可以啦)
import store from '@/store'
var webSocket = null;
var globalCallback = null;
export function initWebSocket (url) {
if ("WebSocket" in window) {
webSocket = new WebSocket(url);
} else {
alert("该浏览器不支持websocket!");
}
webSocket.onopen = function () {
webSocketOpen();
};
webSocket.onmessage = function (msg) {
webSocketOnMessage(msg);
};
webSocket.onclose = function () {
webSocketClose();
};
webSocket.onerror = function () {
console.log("WebSocket连接发生错误");
};
}
export function webSocketOpen () {
console.log("WebSocket连接成功");
}
export function webSocketOnMessage (e) {
store.commit('user/SET_WS_MSG', e)
}
export function webSocketSend (data) {
console.log('发送数据');
webSocket.send(JSON.stringify(data));
}
export function webSocketClose () {
webSocket.close()
console.log("对话连接已关闭");
}
export function sendSock (agentData, callback) {
globalCallback = callback;
switch (webSocket.readyState) {
case webSocket.CONNECTING:
setTimeout(function () {
console.log('正在连接。。。');
webSocketSend(agentData, callback);
}, 1000);
break;
case webSocket.OPEN:
console.log('连接成功');
webSocketSend(agentData);
break;
case webSocket.CLOSING:
setTimeout(function () {
console.log('连接关闭中');
webSocketSend(agentData, callback);
}, 1000);
break;
case webSocket.CLOSED:
console.log('连接关闭/打开失败');
break;
default:
break;
}
}
export default {
initWebSocket,
webSocketClose,
sendSock
};
在vuex中定义存储下接收的数据 websockMsg.js
let state = {
webSocketMsg: ''
};
const mutations = {
SET_WS_MSG: (state, msg) => {
state.webSocketMsg = msg
}
}
getters.js
const getters = {
webSocketMsg: state => state.user.webSocketMsg
}
export default getters
然后在聊天界面中开始使用啦 websocket.vue
<script>
import { initWebSocket, sendSock, webSocketClose } from '@/utils/websocket.js'
export default {
data() {
return {
wsUrl:'ws://地址',
}
},
computed: {
getSocketMsg() {
return this.$store.state.user.webSocketMsg
},
},
watch: {
getSocketMsg: {
handler: function (val) {
this.getConfigResult(val)
},
},
obList: {
handler: function (val) {
this.$nextTick(() => {
this.$refs.chatContent.scrollTop = this.$refs.chatContent.scrollHeight
})
},
},
immediate: true,
},
methods: {
customerDialog() {
initWebSocket(this.wsUrl)
},
getConfigResult(val) { },
sending() {
sendSock('发送的信息')
},
handleClose() {
webSocketClose()
},
},
}
</script>
|