feat: 初始化项目基础结构和配置

添加项目基础文件结构、依赖配置和核心功能模块
集成uni-app+Vue3+TypeScript开发环境
配置ESLint、Prettier、Stylelint等代码规范工具
实现主题管理、路由、状态管理等核心功能
添加登录认证、文件上传等常用API模块
This commit is contained in:
zhangtao
2025-08-09 14:21:42 +08:00
parent fd6b31f53f
commit eb32f03d76
113 changed files with 22539 additions and 0 deletions
+368
View File
@@ -0,0 +1,368 @@
import { Client, type IMessage, type StompSubscription } from "@stomp/stompjs";
import { getAccessToken } from "@/utils/auth";
export interface UseStompOptions {
/** WebSocket 地址,不传时使用 VITE_APP_WS_ENDPOINT 环境变量 */
brokerURL?: string;
/** 用于鉴权的 token,不传时使用 getAccessToken() 的返回值 */
token?: string;
/** 重连延迟,单位毫秒,默认为 8000 */
reconnectDelay?: number;
/** 连接超时时间,单位毫秒,默认为 10000 */
connectionTimeout?: number;
/** 是否开启指数退避重连策略 */
useExponentialBackoff?: boolean;
/** 最大重连次数,默认为 5 */
maxReconnectAttempts?: number;
/** 最大重连延迟,单位毫秒,默认为 60000 */
maxReconnectDelay?: number;
/** 是否开启调试日志 */
debug?: boolean;
}
/**
* STOMP WebSocket连接组合式函数
* 用于管理WebSocket连接的建立、断开、重连和消息订阅
*/
export function useStomp(options: UseStompOptions = {}) {
// 默认值:brokerURL 从环境变量中获取,token 从 getAccessToken() 获取
const defaultBrokerURL = import.meta.env.VITE_APP_WS_ENDPOINT || "";
const brokerURL = ref(options.brokerURL ?? defaultBrokerURL);
// 默认配置参数
const reconnectDelay = options.reconnectDelay ?? 15000; // 默认15秒重连间隔
const connectionTimeout = options.connectionTimeout ?? 10000;
const useExponentialBackoff = options.useExponentialBackoff ?? false;
const maxReconnectAttempts = options.maxReconnectAttempts ?? 3; // 最多重连3次
const maxReconnectDelay = options.maxReconnectDelay ?? 60000;
// 连接状态标记
const isConnected = ref(false);
// 重连尝试次数
const reconnectCount = ref(0);
// 重连计时器
let reconnectTimer: any = null;
// 连接超时计时器
let connectionTimeoutTimer: any = null;
// 存储所有订阅
const subscriptions = new Map<string, StompSubscription>();
// 用于保存 STOMP 客户端的实例
const client = ref<Client | null>(null);
// 防止重复连接的标志
let isConnecting = false;
let isManualDisconnect = false;
/**
* 初始化 STOMP 客户端
*/
const initializeClient = () => {
// 如果客户端已存在且正在连接或已连接,直接返回
if (client.value && (client.value.active || client.value.connected)) {
console.log("STOMP客户端已存在且处于活动状态,跳过初始化");
return;
}
// 检查WebSocket端点是否配置
if (!brokerURL.value) {
console.error("WebSocket连接失败: 未配置WebSocket端点URL");
return;
}
// 每次连接前重新获取最新令牌,不依赖之前的token值
const currentToken = getAccessToken();
// 检查令牌是否为空,如果为空则不进行连接
if (!currentToken) {
console.error("WebSocket连接失败:授权令牌为空,请先登录");
return;
}
// 如果有旧的客户端,先清理
if (client.value) {
try {
client.value.deactivate();
} catch (error) {
console.warn("清理旧客户端时出错:", error);
}
client.value = null;
}
// 创建 STOMP 客户端
client.value = new Client({
brokerURL: brokerURL.value,
connectHeaders: {
Authorization: `Bearer ${currentToken}`,
},
debug: options.debug ? console.log : () => {},
reconnectDelay: 0, // 禁用内置重连机制,使用自定义重连
heartbeatIncoming: 4000,
heartbeatOutgoing: 4000,
});
// 设置连接监听器
client.value.onConnect = () => {
isConnected.value = true;
isConnecting = false;
reconnectCount.value = 0;
clearTimeout(connectionTimeoutTimer);
clearTimeout(reconnectTimer);
console.log("WebSocket连接已建立");
};
// 设置断开连接监听器
client.value.onDisconnect = () => {
isConnected.value = false;
isConnecting = false;
console.log("WebSocket连接已断开");
// 如果不是手动断开且未达到最大重连次数,则尝试重连
if (!isManualDisconnect && reconnectCount.value < maxReconnectAttempts) {
handleReconnect();
}
};
// 设置 Web Socket 关闭监听器
client.value.onWebSocketClose = (event: CloseEvent) => {
isConnected.value = false;
isConnecting = false;
console.log(`WebSocket已关闭: ${event?.code} ${event?.reason}`);
// 如果是手动断开,不要重连
if (isManualDisconnect) {
console.log("手动断开连接,不进行重连");
return;
}
// 如果是授权问题导致的关闭,尝试重连
if (
(event?.code === 1000 || event?.code === 1006 || event?.code === 1008) &&
reconnectCount.value < maxReconnectAttempts
) {
console.log("检测到连接异常关闭,将尝试重连");
// 通过 handleReconnect 统一处理重连,避免重复计数
handleReconnect();
}
};
// 设置错误监听器
client.value.onStompError = (frame: any) => {
console.error("STOMP错误:", frame.headers, frame.body);
isConnecting = false;
// 检查是否是授权错误
if (
frame.headers?.message?.includes("Unauthorized") ||
frame.body?.includes("Unauthorized") ||
frame.body?.includes("Token")
) {
console.warn("WebSocket授权错误,请检查登录状态");
// 授权错误不进行重连
isManualDisconnect = true;
}
};
};
/**
* 处理重连逻辑
*/
const handleReconnect = () => {
// 如果已经在连接中或手动断开,不重连
if (isConnecting || isManualDisconnect) {
return;
}
if (reconnectCount.value >= maxReconnectAttempts) {
console.error(`已达到最大重连次数(${maxReconnectAttempts}),停止重连`);
return;
}
reconnectCount.value++;
console.log(`准备重连(${reconnectCount.value}/${maxReconnectAttempts})...`);
// 使用指数退避策略增加重连间隔
const delay = useExponentialBackoff
? Math.min(reconnectDelay * Math.pow(2, reconnectCount.value - 1), maxReconnectDelay)
: reconnectDelay;
// 清除之前的计时器
if (reconnectTimer) {
clearTimeout(reconnectTimer);
}
// 设置重连计时器
reconnectTimer = setTimeout(() => {
if (!isConnected.value && !isManualDisconnect && !isConnecting) {
console.log(`开始重连...`);
connect();
}
}, delay);
};
// 监听 brokerURL 的变化,若地址改变则重新初始化
watch(brokerURL, (newURL, oldURL) => {
if (newURL !== oldURL) {
console.log(`brokerURL changed from ${oldURL} to ${newURL}`);
// 断开当前连接,重新激活客户端
if (client.value && client.value.connected) {
client.value.deactivate();
}
brokerURL.value = newURL;
initializeClient(); // 重新初始化客户端
}
});
// 初始化客户端
initializeClient();
/**
* 激活连接(如果已经连接或正在激活则直接返回)
*/
const connect = () => {
// 重置手动断开标志
isManualDisconnect = false;
// 检查是否有配置WebSocket端点
if (!brokerURL.value) {
console.error("WebSocket连接失败: 未配置WebSocket端点URL");
return;
}
// 防止重复连接
if (isConnecting) {
console.log("WebSocket正在连接中,跳过重复连接请求");
return;
}
if (!client.value) {
initializeClient();
}
if (!client.value) {
console.error("STOMP客户端初始化失败");
return;
}
// 避免重复连接:检查是否已连接
if (client.value.connected) {
console.log("WebSocket已经连接,跳过重复连接");
isConnected.value = true;
return;
}
// 设置连接标志
isConnecting = true;
// 设置连接超时
clearTimeout(connectionTimeoutTimer);
connectionTimeoutTimer = setTimeout(() => {
if (!isConnected.value && isConnecting) {
console.warn("WebSocket连接超时");
isConnecting = false;
if (!isManualDisconnect && reconnectCount.value < maxReconnectAttempts) {
handleReconnect();
}
}
}, connectionTimeout);
try {
client.value.activate();
console.log("正在建立WebSocket连接...");
} catch (error) {
console.error("激活WebSocket连接失败:", error);
isConnecting = false;
}
};
/**
* 订阅指定主题
* @param destination 目标主题地址
* @param callback 接收到消息时的回调函数
* @returns 返回订阅 id,用于后续取消订阅
*/
const subscribe = (destination: string, callback: (_message: IMessage) => void): string => {
if (!client.value || !client.value.connected) {
console.warn(`尝试订阅 ${destination} 失败: 客户端未连接`);
return "";
}
try {
const subscription = client.value.subscribe(destination, callback);
const subscriptionId = subscription.id;
subscriptions.set(subscriptionId, subscription);
console.log(`订阅成功: ${destination}, ID: ${subscriptionId}`);
return subscriptionId;
} catch (error) {
console.error(`订阅 ${destination} 失败:`, error);
return "";
}
};
/**
* 取消订阅
* @param subscriptionId 订阅 id
*/
const unsubscribe = (subscriptionId: string) => {
const subscription = subscriptions.get(subscriptionId);
if (subscription) {
subscription.unsubscribe();
subscriptions.delete(subscriptionId);
console.log(`已取消订阅: ${subscriptionId}`);
}
};
/**
* 断开WebSocket连接
*/
const disconnect = () => {
// 设置手动断开标志
isManualDisconnect = true;
// 清除所有计时器
if (reconnectTimer) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
if (connectionTimeoutTimer) {
clearTimeout(connectionTimeoutTimer);
connectionTimeoutTimer = null;
}
// 清除所有订阅
for (const [id, subscription] of subscriptions.entries()) {
try {
subscription.unsubscribe();
} catch (error) {
console.warn(`取消订阅 ${id} 时出错:`, error);
}
}
subscriptions.clear();
// 断开连接
if (client.value) {
try {
if (client.value.connected || client.value.active) {
client.value.deactivate();
console.log("WebSocket连接已主动断开");
}
} catch (error) {
console.error("断开WebSocket连接时出错:", error);
}
client.value = null;
}
isConnected.value = false;
isConnecting = false;
reconnectCount.value = 0;
};
return {
isConnected,
connect,
subscribe,
unsubscribe,
disconnect,
};
}
+51
View File
@@ -0,0 +1,51 @@
export interface TabbarItem {
name: string;
value: number | null;
active: boolean;
title: string;
icon: string;
}
const tabbarItems = ref<TabbarItem[]>([
{ name: "home", value: null, active: true, title: "首页", icon: "home" },
{ name: "mine", value: null, active: false, title: "我的", icon: "user" },
]);
export function useTabbar() {
const tabbarList = computed(() => tabbarItems.value);
const activeTabbar = computed(() => {
const item = tabbarItems.value.find((item) => item.active);
return item || tabbarItems.value[0];
});
const getTabbarItemValue = (name: string) => {
const item = tabbarItems.value.find((item) => item.name === name);
return item && item.value ? item.value : null;
};
const setTabbarItem = (name: string, value: number) => {
const tabbarItem = tabbarItems.value.find((item) => item.name === name);
if (tabbarItem) {
tabbarItem.value = value;
}
};
const setTabbarItemActive = (name: string) => {
tabbarItems.value.forEach((item) => {
if (item.name === name) {
item.active = true;
} else {
item.active = false;
}
});
};
return {
tabbarList,
activeTabbar,
getTabbarItemValue,
setTabbarItem,
setTabbarItemActive,
};
}
+178
View File
@@ -0,0 +1,178 @@
import type { ConfigProviderThemeVars } from "wot-design-uni";
// 定义主题色选项
export interface ThemeColorOption {
name: string;
value: string;
primary: string;
}
// 预定义的主题色选项
export const themeColorOptions: ThemeColorOption[] = [
{ name: "默认蓝", value: "blue", primary: "#4D7FFF" },
{ name: "活力橙", value: "orange", primary: "#FF7D00" },
{ name: "薄荷绿", value: "green", primary: "#07C160" },
{ name: "樱花粉", value: "pink", primary: "#FF69B4" },
{ name: "紫罗兰", value: "purple", primary: "#8A2BE2" },
{ name: "朱砂红", value: "red", primary: "#FF4757" },
];
export function useTheme() {
// 状态定义
const theme = ref<"light" | "dark">("light");
const followSystem = ref(true); // 是否跟随系统主题
const hasUserSet = ref(false); // 用户是否手动设置过主题
const currentThemeColor = ref<ThemeColorOption>(themeColorOptions[0]);
const showThemeColorSheet = ref(false);
const themeVars = reactive<ConfigProviderThemeVars>({
darkBackground: "#0f0f0f",
darkBackground2: "#1a1a1a",
darkBackground3: "#242424",
darkBackground4: "#2f2f2f",
darkBackground5: "#3d3d3d",
darkBackground6: "#4a4a4a",
darkBackground7: "#606060",
darkColor: "#ffffff",
darkColor2: "#e0e0e0",
darkColor3: "#a0a0a0",
colorTheme: themeColorOptions[0].primary,
});
// 计算属性
const isDark = computed(() => theme.value === "dark");
/* 手动切换主题 */
function toggleTheme(mode?: "light" | "dark") {
theme.value = mode || (theme.value === "light" ? "dark" : "light");
hasUserSet.value = true; // 标记用户已手动设置
followSystem.value = false; // 不再跟随系统
setNavigationBarColor();
}
/* 设置是否跟随系统主题 */
function setFollowSystem(follow: boolean) {
followSystem.value = follow;
if (follow) {
hasUserSet.value = false;
initTheme(); // 重新获取系统主题
}
}
/* 设置导航栏颜色 */
function setNavigationBarColor() {
uni.setNavigationBarColor({
frontColor: theme.value === "light" ? "#000000" : "#ffffff",
backgroundColor: theme.value === "light" ? "#ffffff" : "#000000",
});
}
/* 设置主题色 */
function setCurrentThemeColor(color: ThemeColorOption) {
currentThemeColor.value = color;
themeVars.colorTheme = color.primary;
}
/* 获取系统主题 */
function getSystemTheme(): "light" | "dark" {
try {
// #ifdef MP-WEIXIN
// 微信小程序使用 getAppBaseInfo
const appBaseInfo = uni.getAppBaseInfo();
if (appBaseInfo && appBaseInfo.theme) {
return appBaseInfo.theme as "light" | "dark";
}
// #endif
// #ifndef MP-WEIXIN
// 其他平台使用 getSystemInfoSync
const systemInfo = uni.getSystemInfoSync();
if (systemInfo && systemInfo.theme) {
return systemInfo.theme as "light" | "dark";
}
// #endif
} catch (error) {
console.warn("获取系统主题失败:", error);
}
return "light"; // 默认返回 light
}
/* 初始化主题 */
function initTheme() {
// 如果用户已手动设置且不跟随系统,保持当前主题
if (hasUserSet.value && !followSystem.value) {
console.log("使用用户设置的主题:", theme.value);
setNavigationBarColor();
return;
}
// 获取系统主题
const systemTheme = getSystemTheme();
// 如果是首次启动或跟随系统,使用系统主题
if (!hasUserSet.value || followSystem.value) {
theme.value = systemTheme;
if (!hasUserSet.value) {
followSystem.value = true;
console.log("首次启动,使用系统主题:", theme.value);
} else {
console.log("跟随系统主题:", theme.value);
}
}
setNavigationBarColor();
}
/* 打开主题色选择 */
function openThemeColorPicker() {
showThemeColorSheet.value = true;
}
/* 关闭主题色选择 */
function closeThemeColorPicker() {
showThemeColorSheet.value = false;
}
/* 选择主题色 */
function selectThemeColor(option: ThemeColorOption) {
setCurrentThemeColor(option);
closeThemeColorPicker();
}
// 检查函数是否存在的工具函数
const isFunction = (fn: any): boolean => typeof fn === "function";
onBeforeMount(() => {
initTheme();
if (isFunction(uni.onThemeChange)) {
uni.onThemeChange((res) => {
toggleTheme(res.theme);
});
}
});
onUnmounted(() => {
if (isFunction(uni.offThemeChange)) {
uni.offThemeChange((res) => {
toggleTheme(res.theme);
});
}
});
return {
theme: computed(() => theme.value),
isDark,
followSystem: computed(() => followSystem.value),
hasUserSet: computed(() => hasUserSet.value),
currentThemeColor: computed(() => currentThemeColor.value),
showThemeColorSheet,
themeVars,
themeColorOptions,
initTheme,
toggleTheme,
setFollowSystem,
openThemeColorPicker,
closeThemeColorPicker,
selectThemeColor,
};
}
+159
View File
@@ -0,0 +1,159 @@
/**
* 微信授权服务
* 处理微信登录授权、获取用户信息等功能
*/
import { ref } from "vue";
import { getAccessToken } from "@/utils/auth";
export function useWechat() {
// 定义微信授权状态
const authState = ref({
isLogining: false,
authDenied: false,
});
/**
* 获取微信登录凭证code
* @returns Promise 返回登录凭证code
*/
const getLoginCode = (): Promise<string> => {
return new Promise((resolve, reject) => {
// #ifdef MP-WEIXIN
uni.login({
provider: "weixin",
success: (res) => {
if (res.code) {
resolve(res.code);
} else {
reject(new Error("获取微信登录凭证失败"));
}
},
fail: (err) => {
reject(err);
},
});
// #endif
// #ifndef MP-WEIXIN
reject(new Error("当前环境不支持微信登录"));
// #endif
});
};
/**
* 获取微信用户手机号
* @param e 微信授权返回的事件对象
* @returns Promise 返回包含手机号加密数据的对象
*/
const getPhoneNumber = (
e: any
): Promise<{ code: string; encryptedData?: string; iv?: string }> => {
return new Promise((resolve, reject) => {
authState.value.isLogining = true;
// 判断授权是否成功
if (e.detail.errMsg !== "getPhoneNumber:ok") {
authState.value.isLogining = false;
authState.value.authDenied = true;
reject(new Error("用户拒绝授权"));
return;
}
// 获取登录凭证code
getLoginCode()
.then((code) => {
// 在微信小程序环境下,可以获取encryptedData和iv
// #ifdef MP-WEIXIN
resolve({
code,
encryptedData: e.detail.encryptedData,
iv: e.detail.iv,
});
// #endif
// 其他环境或新版本接口
// #ifndef MP-WEIXIN
resolve({
code,
// 新版本接口在e.detail.code中包含手机号获取凭证
...(e.detail.code ? { phoneCode: e.detail.code } : {}),
});
// #endif
})
.catch((err) => {
reject(err);
})
.finally(() => {
authState.value.isLogining = false;
});
});
};
/**
* 检查会话有效性
* @returns Promise 返回会话是否有效
*/
const checkSession = (): Promise<boolean> => {
return new Promise((resolve) => {
const token = getAccessToken();
if (!token) {
resolve(false);
return;
}
// 调用后端接口验证token有效性
uni.request({
url: "/api/v1/auth/check-session",
method: "GET",
header: {
Authorization: `Bearer ${token}`,
},
success: (res: any) => {
if (res.statusCode === 200 && res.data.valid) {
resolve(true);
} else {
resolve(false);
}
},
fail: () => {
resolve(false);
},
});
});
};
/**
* 获取用户头像昵称
* 注意:此接口已于2021年弃用,仅作为兼容保留
* 推荐使用button组件的open-type="chooseAvatar"让用户选择头像
*/
const getUserProfile = (): Promise<any> => {
return new Promise((resolve, reject) => {
// #ifdef MP-WEIXIN
uni.getUserProfile({
desc: "用于完善用户资料",
success: (res) => {
resolve(res.userInfo);
},
fail: (err) => {
reject(err);
},
});
// #endif
// #ifndef MP-WEIXIN
reject(new Error("当前环境不支持获取用户信息"));
// #endif
});
};
return {
authState,
getLoginCode,
getPhoneNumber,
checkSession,
getUserProfile,
};
}