9/10
This commit is contained in:
@@ -26,18 +26,61 @@ export const initSSE = (url: any) => {
|
||||
|
||||
watch(data, () => {
|
||||
if (!data.value) return;
|
||||
const notice = JSON.parse(data.value);
|
||||
useNoticeStore().addNotice({
|
||||
message: notice.message,
|
||||
read: false,
|
||||
time: new Date().toLocaleString()
|
||||
});
|
||||
ElNotification({
|
||||
title: notice.title,
|
||||
message: notice.message,
|
||||
type: notice.type,
|
||||
duration: 3000
|
||||
});
|
||||
data.value = null;
|
||||
const notice = tryParseJson(data.value);
|
||||
if (typeof notice === 'string') {
|
||||
useNoticeStore().addNotice({
|
||||
message: notice,
|
||||
read: false,
|
||||
time: new Date().toLocaleString()
|
||||
});
|
||||
ElNotification({
|
||||
title: '消息',
|
||||
message: notice,
|
||||
type: 'success',
|
||||
duration: 3000
|
||||
});
|
||||
data.value = null;
|
||||
return;
|
||||
} else {
|
||||
// 此处 notice 类型为 Record<string, unknown>,安全取出属性
|
||||
const title = typeof notice.title === 'string' ? notice.title : '消息';
|
||||
const message = typeof notice.message === 'string' ? notice.message : '';
|
||||
const type = typeof notice.type === 'string' ? notice.type : 'info';
|
||||
useNoticeStore().addNotice({
|
||||
message,
|
||||
read: false,
|
||||
time: new Date().toLocaleString()
|
||||
});
|
||||
ElNotification({
|
||||
title,
|
||||
message,
|
||||
type: type as 'success' | 'warning' | 'info' | 'error',
|
||||
duration: 3000
|
||||
});
|
||||
data.value = null;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 尝试解析后端返回的字符串
|
||||
* 如果是合法JSON对象 → 返回 Record<string, unknown>
|
||||
* 否则(数组/null/基础值/非JSON字符串) → 返回原字符串
|
||||
* @param str 后端传过来的字符串
|
||||
*/
|
||||
function tryParseJson(str: string): string | Record<string, unknown> {
|
||||
if (typeof str !== 'string' || str === '') return str;
|
||||
|
||||
const trimStr = str.trim();
|
||||
if (trimStr === '') return str;
|
||||
try {
|
||||
const parsed = JSON.parse(trimStr);
|
||||
// 只有"纯对象"才返回对象,数组/null/基础值等统一当作字符串处理
|
||||
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
return parsed as Record<string, unknown>;
|
||||
}
|
||||
return str;
|
||||
} catch {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user