前端代码格式化

This commit is contained in:
2026-02-19 11:46:27 +08:00
parent d310a29c03
commit f0f0763ceb
101 changed files with 8952 additions and 13203 deletions
+5 -5
View File
@@ -1,9 +1,9 @@
import { useI18n as useVueI18n } from "vue-i18n";
import { useI18nStore } from "@/stores/modules/i18n";
import { useI18n as useVueI18n } from 'vue-i18n'
import { useI18nStore } from '@/stores/modules/i18n'
export function useI18n() {
const { t, locale, availableLocales } = useVueI18n();
const i18nStore = useI18nStore();
const { t, locale, availableLocales } = useVueI18n()
const i18nStore = useI18nStore()
return {
t,
@@ -12,5 +12,5 @@ export function useI18n() {
setLocale: i18nStore.setLocale,
currentLocale: i18nStore.currentLocale,
localeLabel: i18nStore.localeLabel,
};
}
}
+75 -95
View File
@@ -1,5 +1,5 @@
import { ref, reactive, computed, onMounted } from "vue";
import { message } from "ant-design-vue";
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
/**
* 表格通用hooks
@@ -15,36 +15,25 @@ import { message } from "ant-design-vue";
* @returns {Object} 返回表格相关的状态和方法
*/
export function useTable(options = {}) {
const {
api,
searchForm: initialSearchForm = {},
columns = [],
rowKey = "id",
needPagination = true,
paginationConfig = {},
needSelection = false,
immediateLoad = true,
} = options;
const { api, searchForm: initialSearchForm = {}, columns = [], rowKey = 'id', needPagination = true, paginationConfig = {}, needSelection = false, immediateLoad = true } = options
// 表格引用
const tableRef = ref(null);
const tableRef = ref(null)
// 搜索表单
const searchForm = reactive({ ...initialSearchForm });
const searchForm = reactive({ ...initialSearchForm })
// 表格数据
const tableData = ref([]);
const tableData = ref([])
// 加载状态
const loading = ref(false);
const loading = ref(false)
// 选中的行数据
const selectedRows = ref([]);
const selectedRows = ref([])
// 选中的行keys
const selectedRowKeys = computed(() =>
selectedRows.value.map((item) => item[rowKey]),
);
const selectedRowKeys = computed(() => selectedRows.value.map((item) => item[rowKey]))
// 分页配置
const defaultPaginationConfig = {
@@ -53,180 +42,171 @@ export function useTable(options = {}) {
total: 0,
showSizeChanger: true,
showTotal: (total) => `${total}`,
pageSizeOptions: ["20", "50", "100", "200"],
};
pageSizeOptions: ['20', '50', '100', '200'],
}
const pagination = reactive({
...defaultPaginationConfig,
...paginationConfig,
});
})
// 行选择配置
const rowSelection = computed(() => {
if (!needSelection) return null;
if (!needSelection) return null
return {
selectedRowKeys: selectedRowKeys.value,
onChange: (keys, rows) => {
selectedRows.value = rows;
selectedRows.value = rows
},
};
});
}
})
// 行选择事件处理(用于scTable的@select事件)
const handleSelectChange = (record, selected, selectedRows) => {
if (!needSelection) return;
if (!needSelection) return
if (selected) {
selectedRows.value.push(record);
selectedRows.value.push(record)
} else {
const index = selectedRows.value.findIndex(
(item) => item[rowKey] === record[rowKey],
);
const index = selectedRows.value.findIndex((item) => item[rowKey] === record[rowKey])
if (index > -1) {
selectedRows.value.splice(index, 1);
selectedRows.value.splice(index, 1)
}
}
};
}
// 全选/取消全选处理(用于scTable的@selectAll事件)
const handleSelectAll = (selected, selectedRows, changeRows) => {
if (!needSelection) return;
if (!needSelection) return
if (selected) {
changeRows.forEach((record) => {
if (
!selectedRows.value.find(
(item) => item[rowKey] === record[rowKey],
)
) {
selectedRows.value.push(record);
if (!selectedRows.value.find((item) => item[rowKey] === record[rowKey])) {
selectedRows.value.push(record)
}
});
})
} else {
changeRows.forEach((record) => {
const index = selectedRows.value.findIndex(
(item) => item[rowKey] === record[rowKey],
);
const index = selectedRows.value.findIndex((item) => item[rowKey] === record[rowKey])
if (index > -1) {
selectedRows.value.splice(index, 1);
selectedRows.value.splice(index, 1)
}
});
})
}
};
}
// 加载数据
const loadData = async (params = {}) => {
if (!api) {
console.warn("useTable: 未提供api函数,无法加载数据");
return;
console.warn('useTable: 未提供api函数,无法加载数据')
return
}
loading.value = true;
loading.value = true
try {
const requestParams = {
...searchForm,
...params,
};
}
// 如果需要分页,添加分页参数
if (needPagination) {
requestParams.page = pagination.current;
requestParams.limit = pagination.pageSize;
requestParams.page = pagination.current
requestParams.limit = pagination.pageSize
}
// 调用API函数,确保this上下文正确
const res = await api(requestParams);
const res = await api(requestParams)
if (res.code === 200) {
// 如果是分页数据
if (needPagination) {
tableData.value = res.data?.list || [];
pagination.total = res.data?.total || 0;
tableData.value = res.data?.list || []
pagination.total = res.data?.total || 0
} else {
// 非分页数据(如树形数据)
// 确保数据是数组,如果不是数组则包装成数组
const data = res.data;
const data = res.data
if (Array.isArray(data)) {
tableData.value = data;
} else if (data && typeof data === "object") {
tableData.value = data
} else if (data && typeof data === 'object') {
// 如果返回的是对象,可能包含 list 或 items 等字段
tableData.value =
data.list || data.items || data.data || [];
tableData.value = data.list || data.items || data.data || []
} else {
tableData.value = [];
tableData.value = []
}
}
} else {
message.error(res.message || "加载数据失败");
message.error(res.message || '加载数据失败')
}
} catch (error) {
console.error("加载数据失败:", error);
message.error("加载数据失败");
console.error('加载数据失败:', error)
message.error('加载数据失败')
} finally {
loading.value = false;
loading.value = false
}
};
}
// 分页变化处理
const handlePaginationChange = ({ page, pageSize }) => {
if (!needPagination) return;
pagination.current = page;
pagination.pageSize = pageSize;
loadData();
};
if (!needPagination) return
pagination.current = page
pagination.pageSize = pageSize
loadData()
}
// 搜索
const handleSearch = () => {
if (needPagination) {
pagination.current = 1;
pagination.current = 1
}
loadData();
};
loadData()
}
// 重置
const handleReset = () => {
// 重置搜索表单为初始值
Object.keys(searchForm).forEach((key) => {
searchForm[key] = initialSearchForm[key];
});
searchForm[key] = initialSearchForm[key]
})
// 清空选择
selectedRows.value = [];
selectedRows.value = []
// 重置分页
if (needPagination) {
pagination.current = 1;
pagination.current = 1
}
// 重新加载数据
loadData();
};
loadData()
}
// 刷新表格
const refreshTable = () => {
loadData();
};
loadData()
}
// 清空选择
const clearSelection = () => {
selectedRows.value = [];
};
selectedRows.value = []
}
// 设置选中行
const setSelectedRows = (rows) => {
selectedRows.value = rows;
};
selectedRows.value = rows
}
// 更新搜索表单
const setSearchForm = (data) => {
Object.assign(searchForm, data);
};
Object.assign(searchForm, data)
}
// 直接设置表格数据(用于特殊场景)
const setTableData = (data) => {
tableData.value = data;
};
tableData.value = data
}
// 组件挂载时自动加载数据
if (immediateLoad) {
onMounted(() => {
loadData();
});
loadData()
})
}
return {
@@ -255,5 +235,5 @@ export function useTable(options = {}) {
setSelectedRows,
setSearchForm,
setTableData,
};
}
}
+108 -108
View File
@@ -1,11 +1,11 @@
import { ref } from "vue";
import { getWebSocket } from "@/utils/websocket";
import { useUserStore } from "@/stores/modules/user";
import { useMessageStore } from "@/stores/modules/message";
import { useDictionaryStore } from "@/stores/modules/dictionary";
import { useNotificationStore } from "@/stores/modules/notification";
import { message, notification } from "ant-design-vue";
import config from "@/config";
import { ref } from 'vue'
import { getWebSocket } from '@/utils/websocket'
import { useUserStore } from '@/stores/modules/user'
import { useMessageStore } from '@/stores/modules/message'
import { useDictionaryStore } from '@/stores/modules/dictionary'
import { useNotificationStore } from '@/stores/modules/notification'
import { message, notification } from 'ant-design-vue'
import config from '@/config'
/**
* WebSocket Composable
@@ -13,13 +13,13 @@ import config from "@/config";
* 处理 WebSocket 连接和消息监听
*/
export function useWebSocket() {
const ws = ref(null);
const userStore = useUserStore();
const messageStore = useMessageStore();
const dictionaryStore = useDictionaryStore();
const notificationStore = useNotificationStore();
const reconnectTimer = ref(null);
const isInitialized = ref(false);
const ws = ref(null)
const userStore = useUserStore()
const messageStore = useMessageStore()
const dictionaryStore = useDictionaryStore()
const notificationStore = useNotificationStore()
const reconnectTimer = ref(null)
const isInitialized = ref(false)
/**
* 初始化 WebSocket 连接
@@ -27,29 +27,29 @@ export function useWebSocket() {
function initWebSocket() {
// 如果已经初始化,不再重复初始化
if (isInitialized.value) {
console.log("WebSocket 已初始化,跳过重复初始化");
return;
console.log('WebSocket 已初始化,跳过重复初始化')
return
}
// 检查用户信息是否完整
if (!userStore.isUserInfoComplete()) {
console.warn("用户信息不完整,等待用户信息加载...");
console.warn('用户信息不完整,等待用户信息加载...')
// 延迟重试,等待用户信息加载
if (reconnectTimer.value) {
clearTimeout(reconnectTimer.value);
clearTimeout(reconnectTimer.value)
}
reconnectTimer.value = setTimeout(() => {
initWebSocket();
}, 1000);
return;
initWebSocket()
}, 1000)
return
}
try {
console.log("开始初始化 WebSocket...", {
console.log('开始初始化 WebSocket...', {
userId: userStore.userInfo.id,
username: userStore.userInfo.username,
});
})
// 使用配置文件中的 WS_URL
// getWebSocket 会自动处理重复连接问题
@@ -59,21 +59,21 @@ export function useWebSocket() {
onMessage: handleMessage,
onError: handleError,
onClose: handleClose,
});
})
// 注册消息处理器
registerMessageHandlers();
registerMessageHandlers()
// 标记为已初始化
isInitialized.value = true;
isInitialized.value = true
// 连接(如果还未连接)
if (ws.value && !ws.value.isConnected) {
ws.value.connect();
ws.value.connect()
}
} catch (error) {
console.error("初始化 WebSocket 失败:", error);
isInitialized.value = false;
console.error('初始化 WebSocket 失败:', error)
isInitialized.value = false
}
}
@@ -81,37 +81,37 @@ export function useWebSocket() {
* 注册所有消息处理器
*/
function registerMessageHandlers() {
if (!ws.value) return;
if (!ws.value) return
// 字典更新
ws.value.on("dictionary_update", handleDictionaryUpdate);
ws.value.on("dictionary_item_update", handleDictionaryItemUpdate);
ws.value.on('dictionary_update', handleDictionaryUpdate)
ws.value.on('dictionary_item_update', handleDictionaryItemUpdate)
// 系统通知
ws.value.on("notification", handleNotification);
ws.value.on('notification', handleNotification)
// 数据更新
ws.value.on("data_update", handleDataUpdate);
ws.value.on('data_update', handleDataUpdate)
// 心跳响应
ws.value.on("heartbeat_response", handleHeartbeatResponse);
ws.value.on('heartbeat_response', handleHeartbeatResponse)
// 连接确认
ws.value.on("connected", handleConnected);
ws.value.on('connected', handleConnected)
}
/**
* 取消注册所有消息处理器
*/
function unregisterMessageHandlers() {
if (!ws.value) return;
if (!ws.value) return
ws.value.off("dictionary_update");
ws.value.off("dictionary_item_update");
ws.value.off("notification");
ws.value.off("data_update");
ws.value.off("heartbeat_response");
ws.value.off("connected");
ws.value.off('dictionary_update')
ws.value.off('dictionary_item_update')
ws.value.off('notification')
ws.value.off('data_update')
ws.value.off('heartbeat_response')
ws.value.off('connected')
}
/**
@@ -119,41 +119,41 @@ export function useWebSocket() {
* 注意:认证已在连接时通过 URL 参数完成,无需单独发送 auth 事件
*/
function handleOpen(event) {
console.log("WebSocket 连接已建立(已通过 URL 参数完成认证)", event);
console.log('WebSocket 连接已建立(已通过 URL 参数完成认证)', event)
}
/**
* 处理连接确认
*/
function handleConnected(data) {
console.log("WebSocket 连接已确认", data);
message.success("实时连接已建立");
console.log('WebSocket 连接已确认', data)
message.success('实时连接已建立')
}
/**
* 处理接收消息
*/
function handleMessage(message, event) {
console.log("收到 WebSocket 消息:", message);
console.log('收到 WebSocket 消息:', message)
}
/**
* 处理错误
*/
function handleError(error) {
console.error("WebSocket 错误:", error);
message.error("实时连接出现错误,正在重连...");
console.error('WebSocket 错误:', error)
message.error('实时连接出现错误,正在重连...')
}
/**
* 处理连接关闭
*/
function handleClose(event) {
console.log("WebSocket 连接已关闭", event);
console.log('WebSocket 连接已关闭', event)
// 如果不是手动关闭,显示提示
if (event.code !== 1000) {
message.warning("实时连接已断开");
message.warning('实时连接已断开')
}
}
@@ -161,64 +161,64 @@ export function useWebSocket() {
* 处理心跳响应
*/
function handleHeartbeatResponse(data) {
console.log("收到心跳响应:", data);
console.log('收到心跳响应:', data)
}
/**
* 处理系统通知
*/
function handleNotification(data) {
console.log("收到系统通知:", data);
console.log('收到系统通知:', data)
const { title, message: content, type, timestamp, ...rest } = data;
const { title, message: content, type, timestamp, ...rest } = data
// 构建通知数据格式
const notificationData = {
id: rest.id || Date.now(),
title: title || "系统通知",
content: content || "",
type: type || "info",
category: rest.category || "system",
title: title || '系统通知',
content: content || '',
type: type || 'info',
category: rest.category || 'system',
is_read: false,
created_at: rest.created_at || new Date().toISOString(),
...rest,
};
}
// 更新通知 store
notificationStore.handleWebSocketMessage({
type: "notification",
type: 'notification',
data: notificationData,
});
})
// 添加到消息 store(保持兼容性)
messageStore.addMessage({
type: type || "notification",
title: title || "系统通知",
content: content || "",
type: type || 'notification',
title: title || '系统通知',
content: content || '',
timestamp: timestamp || Date.now(),
});
})
// 显示通知(根据类型)
const notificationConfig = {
message: title || "系统通知",
message: title || '系统通知',
description: content,
duration: 4.5,
placement: "topRight",
};
placement: 'topRight',
}
// 根据类型设置不同样式
switch (type) {
case "success":
notification.success(notificationConfig);
break;
case "error":
notification.error(notificationConfig);
break;
case "warning":
notification.warning(notificationConfig);
break;
case 'success':
notification.success(notificationConfig)
break
case 'error':
notification.error(notificationConfig)
break
case 'warning':
notification.warning(notificationConfig)
break
default:
notification.info(notificationConfig);
notification.info(notificationConfig)
}
}
@@ -226,24 +226,24 @@ export function useWebSocket() {
* 处理数据更新
*/
async function handleDataUpdate(data) {
console.log("收到数据更新:", data);
console.log('收到数据更新:', data)
const { resource_type, action, timestamp } = data;
const { resource_type, action, timestamp } = data
// 添加到消息 store
messageStore.handleDataUpdate(data);
messageStore.handleDataUpdate(data)
// 根据资源类型执行相应操作
switch (resource_type) {
case "dictionary":
case "dictionary_item":
case 'dictionary':
case 'dictionary_item':
// 刷新字典缓存
try {
await dictionaryStore.refresh(true);
await dictionaryStore.refresh(true)
} catch (error) {
console.error("刷新字典缓存失败:", error);
console.error('刷新字典缓存失败:', error)
}
break;
break
// 可以添加其他资源类型的处理
}
}
@@ -252,16 +252,16 @@ export function useWebSocket() {
* 处理字典分类更新
*/
async function handleDictionaryUpdate(data) {
console.log("字典分类已更新:", data);
console.log('字典分类已更新:', data)
try {
// 刷新字典缓存
await dictionaryStore.refresh(true);
await dictionaryStore.refresh(true)
// 显示通知
message.success("字典数据已更新");
message.success('字典数据已更新')
} catch (error) {
console.error("刷新字典缓存失败:", error);
console.error('刷新字典缓存失败:', error)
}
}
@@ -269,16 +269,16 @@ export function useWebSocket() {
* 处理字典项更新
*/
async function handleDictionaryItemUpdate(data) {
console.log("字典项已更新:", data);
console.log('字典项已更新:', data)
try {
// 刷新字典缓存
await dictionaryStore.refresh(true);
await dictionaryStore.refresh(true)
// 显示通知
message.success("字典数据已更新");
message.success('字典数据已更新')
} catch (error) {
console.error("刷新字典缓存失败:", error);
console.error('刷新字典缓存失败:', error)
}
}
@@ -287,9 +287,9 @@ export function useWebSocket() {
*/
function send(type, data) {
if (ws.value && ws.value.isConnected) {
ws.value.send(type, data);
ws.value.send(type, data)
} else {
console.warn("WebSocket 未连接,无法发送消息");
console.warn('WebSocket 未连接,无法发送消息')
}
}
@@ -299,37 +299,37 @@ export function useWebSocket() {
function closeWebSocket() {
// 清除重试定时器
if (reconnectTimer.value) {
clearTimeout(reconnectTimer.value);
reconnectTimer.value = null;
clearTimeout(reconnectTimer.value)
reconnectTimer.value = null
}
if (ws.value) {
// 取消注册消息处理器
unregisterMessageHandlers();
unregisterMessageHandlers()
ws.value.disconnect();
ws.value = null;
ws.value.disconnect()
ws.value = null
}
// 重置初始化标记
isInitialized.value = false;
isInitialized.value = false
}
/**
* 重新连接 WebSocket
*/
function reconnect() {
closeWebSocket();
closeWebSocket()
setTimeout(() => {
initWebSocket();
}, 1000);
initWebSocket()
}, 1000)
}
/**
* 检查连接状态
*/
function isConnected() {
return ws.value && ws.value.isConnected;
return ws.value && ws.value.isConnected
}
return {
@@ -339,5 +339,5 @@ export function useWebSocket() {
reconnect,
isConnected,
send,
};
}
}