98 lines
2.3 KiB
JavaScript
98 lines
2.3 KiB
JavaScript
export const namespaced = true
|
||
|
||
export const state = () => ({
|
||
socket: null,
|
||
isConnected: false,
|
||
messages: [],
|
||
notices: [],
|
||
count: "0"
|
||
})
|
||
|
||
export const mutations = {
|
||
WEBSOCKET_INIT(state, url) {
|
||
state.socket = new WebSocket(url);
|
||
state.socket.onopen = function() {
|
||
console.log("WebSocket连接成功");
|
||
};
|
||
// 注意:这里不再直接处理 onmessage,而是在 action 中处理
|
||
state.socket.onerror = function() {
|
||
console.log("WebSocket连接发生错误");
|
||
};
|
||
state.socket.onclose = function(e) {
|
||
console.log("connection closed (" + e.code + ")");
|
||
};
|
||
},
|
||
|
||
SET_SOCKET_ONMESSAGE(state, handler) {
|
||
// 设置 WebSocket 的消息处理函数
|
||
if (state.socket) {
|
||
state.socket.onmessage = handler;
|
||
}
|
||
},
|
||
|
||
WEBSOCKET_SEND(state, msg) {
|
||
if (state.socket) {
|
||
state.socket.send(msg);
|
||
}
|
||
},
|
||
|
||
WEBSOCKET_CLOSE(state) {
|
||
if (state.socket) {
|
||
state.socket.close();
|
||
state.socket = null;
|
||
}
|
||
},
|
||
|
||
SET_MESSAGE(state, msg) {
|
||
state.messages = msg;
|
||
},
|
||
|
||
ADD_MESSAGE(state, message) {
|
||
// 使用展开运算符创建新数组而不是直接 push
|
||
state.messages = [...state.messages, message];
|
||
},
|
||
|
||
ADD_NOTICE(state, notice) {
|
||
// 使用展开运算符创建新数组而不是直接 push
|
||
state.notices = [...state.notices, notice];
|
||
},
|
||
|
||
SET_COUNT(state, count) {
|
||
state.count = count;
|
||
}
|
||
}
|
||
|
||
export const actions = {
|
||
websocket_init({ commit, state }, url) {
|
||
commit('WEBSOCKET_INIT', url);
|
||
|
||
// 在 action 中设置 WebSocket 的 onmessage 回调
|
||
if (state.socket) {
|
||
state.socket.onmessage = function(e) {
|
||
console.log(e, '接收到的消息');
|
||
if (e.data.startsWith("C")) {
|
||
commit('SET_COUNT', e.data);
|
||
} else if (e.data.startsWith("系统通知")) {
|
||
commit('ADD_NOTICE', e.data);
|
||
} else if (e.data.startsWith("close")) {
|
||
console.log(e.data);
|
||
} else {
|
||
commit('ADD_MESSAGE', JSON.parse(e.data));
|
||
console.log(state.messages);
|
||
}
|
||
};
|
||
}
|
||
},
|
||
|
||
websocket_send({ commit }, msg) {
|
||
commit('WEBSOCKET_SEND', msg);
|
||
},
|
||
|
||
websocket_close({ commit }) {
|
||
commit('WEBSOCKET_CLOSE');
|
||
},
|
||
|
||
set_message({ commit }, msg) {
|
||
commit('SET_MESSAGE', msg);
|
||
}
|
||
} |