增加群聊功能
This commit is contained in:
@@ -1,17 +1,103 @@
|
||||
import { defineStore } from "pinia";
|
||||
// import * as shopApi from "@/http/api/shop.js";
|
||||
|
||||
// #ifdef H5
|
||||
const socketUrl = "http://192.168.1.42:2348";
|
||||
// #endif
|
||||
// #ifndef H5
|
||||
const socketUrl = "ws://192.168.1.42:2348";
|
||||
// #endif
|
||||
|
||||
// 聊天
|
||||
export const useChatStore = defineStore("chat", {
|
||||
state: () => {
|
||||
return {
|
||||
socketUrl,
|
||||
isConnect: false,
|
||||
socketTask: null,
|
||||
onReceiveMsg:()=>{
|
||||
|
||||
},
|
||||
chatList: [],
|
||||
};
|
||||
},
|
||||
actions: {
|
||||
sendMessage(message) {
|
||||
this.chatList.push(message);
|
||||
init() {
|
||||
if (!this.isConnect) {
|
||||
return uni.showToast({
|
||||
title: "请先连接socket",
|
||||
icon: "none",
|
||||
});
|
||||
}
|
||||
this.sendMessage(
|
||||
{
|
||||
type: "OnbocChat",
|
||||
operate_type: "init",
|
||||
shop_id: uni.getStorageSync("shopId"),
|
||||
token: uni.getStorageSync("iToken").tokenValue || "",
|
||||
},
|
||||
false
|
||||
);
|
||||
},
|
||||
sendMessage(msg, isAutoAppend = true) {
|
||||
if (!this.isConnect) {
|
||||
return uni.showToast({
|
||||
title: "请先连接socket",
|
||||
icon: "none",
|
||||
});
|
||||
}
|
||||
console.log(this.socketTask);
|
||||
const message = isAutoAppend
|
||||
? {
|
||||
type: "OnbocChat",
|
||||
operate_type: "sendMsg",
|
||||
shop_id: uni.getStorageSync("shopId"),
|
||||
token: uni.getStorageSync("iToken").tokenValue || "",
|
||||
...msg,
|
||||
}
|
||||
: msg;
|
||||
this.socketTask.send({
|
||||
data: JSON.stringify(message),
|
||||
success: (res) => {
|
||||
console.log("发送成功", res);
|
||||
},
|
||||
fail: (error) => {
|
||||
console.log("发送失败", error);
|
||||
},
|
||||
});
|
||||
},
|
||||
connectSocket() {
|
||||
this.socketTask = uni.connectSocket({
|
||||
url: socketUrl,
|
||||
success: (res) => {},
|
||||
fail: (res) => {
|
||||
console.log(res);
|
||||
},
|
||||
});
|
||||
|
||||
this.socketTask.onOpen((res) => {
|
||||
this.isConnect = true;
|
||||
this.init();
|
||||
});
|
||||
|
||||
this.socketTask.onMessage((res) => {
|
||||
const data = JSON.parse(res.data);
|
||||
console.log("收到服务器消息", data);
|
||||
if(data.msg){
|
||||
uni.showToast({
|
||||
title: data.msg,
|
||||
icon: "none",
|
||||
});
|
||||
}
|
||||
|
||||
if(data&&data.operate_type=="sendMsg"){
|
||||
this.chatList.unshift(data.data);
|
||||
this.onReceiveMsg(data.data);
|
||||
console.log(this.chatList);
|
||||
}
|
||||
|
||||
});
|
||||
},
|
||||
},
|
||||
unistorage: true, // 开启后对 state 的数据读写都将持久化
|
||||
unistorage: false, // 开启后对 state 的数据读写都将持久化
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user