更新密码找回uniapp

This commit is contained in:
hero920103 committed 2026-11-16 17:22:50 +08:00
1 parent 7f9a66da0f
commit 3fdda89833
1304 files changed
+3503 -26132

No files matched your search

-17
View File
@@ -3,7 +3,6 @@ import { ref, reactive } from 'vue'
import { getCurrentUser } from '@/api/login'
import { logoutSSO, isAuthHandoff } from '@/utils/authClient'
// 用户信息类型
const defaultUser = {
id:'',
account: '',
@@ -19,7 +18,6 @@ export const useAuthStore = defineStore('auth', () => {
const isLoggedIn = ref(!!token.value)
const user = reactive({ ...defaultUser })
// 从缓存加载用户信息
function loadUserFromCache() {
const cachedUser = localStorage.getItem('userInfo')
if (cachedUser) {
@@ -32,34 +30,26 @@ export const useAuthStore = defineStore('auth', () => {
}
}
// 从后端拉取最新用户信息(含租户名称),用于已有会话补充 tenant_name
async function fetchCurrentUser() {
if (!token.value) return
try {
const res = await getCurrentUser()
if (res && res.code === 200 && res.data) {
// 后端没给出企业名时不要用空值覆盖本地已有的名称,
// 否则顶部「当前企业」会突然消失(统一认证会话下尤其容易出现)
const data = { ...res.data }
if (!data.tenant_name) delete data.tenant_name
Object.assign(user, data)
localStorage.setItem('userInfo', JSON.stringify({ ...user }))
}
} catch (e) {
// 静默失败,不影响登录态
console.error('Failed to fetch current user info:', e)
}
}
// 初始化时加载用户信息
loadUserFromCache()
// 若已登录但缺少租户名称,异步从后端补齐;
// 认证交接页除外(此时 token 是旧的,请求会 401 并干扰换码)
if (token.value && !isAuthHandoff()) {
fetchCurrentUser()
}
// 保存登录信息(token 和用户信息)
function setLoginInfo(loginData) {
const userInfo = loginData.user || loginData
@@ -74,7 +64,6 @@ export const useAuthStore = defineStore('auth', () => {
avatar: userInfo.avatar || ''
}
// 使用后端返回的真实 JWT token
const accessToken = loginData.token || ''
token.value = accessToken
@@ -85,26 +74,21 @@ export const useAuthStore = defineStore('auth', () => {
localStorage.setItem('userInfo', JSON.stringify(normalizedUser))
}
// 设置 token(兼容旧代码)
function setToken(newToken) {
token.value = newToken
isLoggedIn.value = true
localStorage.setItem('token', newToken)
}
// 清除登录信息
function clearToken() {
token.value = ''
isLoggedIn.value = false
Object.assign(user, defaultUser)
localStorage.removeItem('token')
localStorage.removeItem('userInfo')
// 统一认证:吊销令牌并跳认证中心完成单点登出(所有调用点自动生效,
// 调用方不要再 router.push('/login'),本地登录页已下线)
logoutSSO()
}
// 检查认证状态
function checkAuth() {
const storedToken = localStorage.getItem('token')
if (storedToken) {
@@ -118,7 +102,6 @@ export const useAuthStore = defineStore('auth', () => {
}
}
// 更新用户信息
function updateUserInfo(userInfo) {
Object.assign(user, userInfo)
localStorage.setItem('userInfo', JSON.stringify(userInfo))
-38
View File
@@ -2,29 +2,11 @@ import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getDictOptions, getDictOptionsBatch, getAllDictOptions } from '@/api/dict'
/**
* 字典 Store(平台端)
*
* 全部字典数据都来自数据库,前端不维护编码清单:
* - 登录后调用一次 loadAll(),把库里所有「启用」字典读进缓存;
* - 页面按库里真实的 dict_code 取值即可(字符串直接写,无需常量文件);
* - 之后在字典管理页新增的字典,第一次被引用时会按需自动加载。
*
* 用法:
* const dictStore = useDictStore()
* dictStore.getDictLabel('payment_order_status', row.status) // 文案
* dictStore.getDictTagType('payment_order_status', row.status) // 标签色
* dictStore.getSelectOptions('payment_channel') // 下拉选项
*/
export const useDictStore = defineStore('dict', () => {
/** dict_code -> 字典项数组(渲染依赖它,必须是响应式的) */
const dictMap = ref({})
/** 已加载过的编码(仅用于去重,不参与渲染) */
let loaded = {}
/** 正在请求中的编码 -> Promise(并发调用复用同一个请求) */
const pending = new Map()
/** 是否已完成全量预热 */
let allLoaded = false
let allPending = null
@@ -36,15 +18,10 @@ export const useDictStore = defineStore('dict', () => {
return dictMap.value[code] || []
}
/** 把入参规范成去重后的编码数组 */
function normalizeCodes(codes) {
return [...new Set((codes || []).map((c) => String(c || '').trim()).filter(Boolean))]
}
/**
* 加载字典(带缓存与并发去重)。
* 请求失败也会标记为已加载,避免页面反复重试;需要重试请先 clearCache。
*/
async function load(codes) {
const list = normalizeCodes(codes)
const missing = list.filter((c) => !loaded[c] && !pending.has(c))
@@ -52,7 +29,6 @@ export const useDictStore = defineStore('dict', () => {
if (missing.length) {
const promise = (async () => {
if (missing.length === 1) {
// 单个字典走专用接口
const code = missing[0]
try {
const res = await getDictOptions(code)
@@ -61,7 +37,6 @@ export const useDictStore = defineStore('dict', () => {
setItems(code, [])
}
} else {
// 多个字典合并成一次请求
try {
const res = await getDictOptionsBatch(missing)
const dicts = res?.code === 200 ? res.data?.dicts || {} : {}
@@ -84,10 +59,6 @@ export const useDictStore = defineStore('dict', () => {
return list.flatMap((c) => itemsOf(c))
}
/**
* 全量预热:一次请求把库里所有启用字典读进缓存(登录后调用一次即可)。
* 之后再新增的字典仍会走 load() 按需加载。
*/
function loadAll() {
if (allLoaded) return Promise.resolve()
if (allPending) return allPending
@@ -103,7 +74,6 @@ export const useDictStore = defineStore('dict', () => {
})
dictMap.value = next
} catch {
// 预热失败不影响使用:后续按需加载
} finally {
allLoaded = true
allPending = null
@@ -112,7 +82,6 @@ export const useDictStore = defineStore('dict', () => {
return allPending
}
/** 同步触发加载(不等待),用于组件 setup/onMounted 里“先渲染后填充” */
function ensure(code) {
const list = normalizeCodes([code])
if (list.some((c) => !loaded[c] && !pending.has(c))) {
@@ -120,20 +89,17 @@ export const useDictStore = defineStore('dict', () => {
}
}
/** 同步取字典项;未加载时顺带触发加载,拿到后由响应式自动刷新 */
function getDictItemsSync(code) {
ensure(code)
return itemsOf(code)
}
/** 值 → 字典项(值按字符串比较,兼容 1 / '1' 混用) */
function getDictItem(code, value) {
if (value === undefined || value === null || value === '') return null
const key = String(value)
return itemsOf(code).find((it) => String(it.item_value) === key) || null
}
/** 值 → 文案;取不到时返回 fallback,未传则原样返回取值 */
function getDictLabel(code, value, fallback) {
const hit = getDictItem(code, value)
if (hit) return hit.item_label
@@ -141,23 +107,19 @@ export const useDictStore = defineStore('dict', () => {
return value === undefined || value === null ? '' : String(value)
}
/** 值 → el-tag 的 type;取不到时返回 fallback(默认 info) */
function getDictTagType(code, value, fallback = 'info') {
const hit = getDictItem(code, value)
return hit && hit.tag_type ? hit.tag_type : fallback
}
/** 值 → 下拉选项 { label, value },供 el-select / el-option 直接使用 */
function getSelectOptions(code) {
return getDictItemsSync(code).map((it) => ({ label: it.item_label, value: it.item_value, tag_type: it.tag_type }))
}
/** 预加载多个字典(一次批量请求) */
function preloadDicts(codes) {
return load(codes)
}
/** 清空缓存:传编码清单个,不传清全部(同时允许重新全量预热) */
function clearCache(code) {
if (code) {
delete loaded[code]
-36
View File
@@ -1,11 +1,9 @@
import { defineStore } from 'pinia';
import { ref, computed, reactive } from 'vue';
// ========== 全局状态 Store ==========
function initState() {
return {
isCollapse: false,
// 手机端抽屉式侧栏是否展开(仅 ≤768px 生效)
mobileAsideOpen: false,
};
}
@@ -18,12 +16,10 @@ export const useAllDataStore = defineStore('allData', () => {
count.value++;
}
// 是否为手机端(≤768px),通过 matchMedia 响应式监听
const mobileQuery = window.matchMedia('(max-width: 768px)');
const isMobile = ref(mobileQuery.matches);
const handleMobileQueryChange = (e) => {
isMobile.value = e.matches;
// 从手机端切回桌面端时,自动收起抽屉侧栏
if (!e.matches) {
state.mobileAsideOpen = false;
}
@@ -31,7 +27,6 @@ export const useAllDataStore = defineStore('allData', () => {
if (typeof mobileQuery.addEventListener === 'function') {
mobileQuery.addEventListener('change', handleMobileQueryChange);
} else {
// 兼容旧版 Safari
mobileQuery.addListener(handleMobileQueryChange);
}
@@ -44,24 +39,12 @@ export const useAllDataStore = defineStore('allData', () => {
};
});
// ========== 多标签页 Tabs Store ==========
import { defineStore as defineTabsStore } from 'pinia';
import { ref as vueRef } from 'vue';
/**
* 多标签页Tabs状态管理
* tabList每个tab结构: {
* title: 标签显示名,
* fullPath: 路由路径(唯一key),
* name: 路由name,
* icon: 图标(可选)
* }
*/
export const useTabsStore = defineTabsStore('tabs', () => {
// 默认标签页:不再固定「首页」,而是由 Main.vue 按当前模块设置成仪表盘
const defaultDashboardPath = vueRef('');
// 从 localStorage 恢复 tabs 状态(兼容旧版本里遗留的 /home 首页标签)
function loadTabsFromStorage() {
try {
const savedTabs = localStorage.getItem('tabs_list');
@@ -77,7 +60,6 @@ export const useTabsStore = defineTabsStore('tabs', () => {
return [];
}
// 保存 tabs 到 localStorage
function saveTabsToStorage(tabs, active) {
try {
localStorage.setItem('tabs_list', JSON.stringify(tabs));
@@ -95,16 +77,12 @@ export const useTabsStore = defineTabsStore('tabs', () => {
savedActiveTab && savedActiveTab !== '/home' ? savedActiveTab : ''
);
// 设置当前模块的默认仪表盘标签:始终排在第一位且不可关闭
function setDefaultTab(tab) {
const path = tab?.fullPath || '';
if (!path) return;
const prevDefault = defaultDashboardPath.value;
defaultDashboardPath.value = path;
// 默认工作台路径变化 = 切换了模块:关闭旧模块的全部 tab,
// 只保留新模块的默认工作台。
// prevDefault 为空(首次设置,如刷新后恢复)时不清空,保留恢复出来的 tabs。
if (prevDefault && prevDefault !== path) {
tabList.value = [tab];
activeTab.value = path;
@@ -126,7 +104,6 @@ export const useTabsStore = defineTabsStore('tabs', () => {
saveTabsToStorage(tabList.value, activeTab.value);
}
// 添加tab,若已存在则激活
function addTab(tab) {
const exist = tabList.value.find((t) => t.fullPath === tab.fullPath);
if (!exist) {
@@ -136,16 +113,13 @@ export const useTabsStore = defineTabsStore('tabs', () => {
saveTabsToStorage(tabList.value, activeTab.value);
}
// 删除指定tab并切换激活tab(默认仪表盘标签不可关闭)
function removeTab(fullPath) {
if (fullPath === defaultDashboardPath.value) return;
const idx = tabList.value.findIndex((t) => t.fullPath === fullPath);
if (idx > -1) {
tabList.value.splice(idx, 1);
// 只在关闭当前激活tab时切换激活tab
if (activeTab.value === fullPath) {
if (tabList.value.length > 0) {
// 优先激活右侧(如无则激活左侧)
const newIdx = idx >= tabList.value.length ? tabList.value.length - 1 : idx;
activeTab.value = tabList.value[newIdx].fullPath;
} else {
@@ -156,7 +130,6 @@ export const useTabsStore = defineTabsStore('tabs', () => {
}
}
// 关闭其他,只留默认仪表盘和当前激活tab
function closeOthers() {
tabList.value = tabList.value.filter(
(t) => t.fullPath === defaultDashboardPath.value || t.fullPath === activeTab.value
@@ -164,7 +137,6 @@ export const useTabsStore = defineTabsStore('tabs', () => {
saveTabsToStorage(tabList.value, activeTab.value);
}
// 关闭左侧(关闭指定tab左侧的所有tab,保留默认仪表盘和目标tab)
function closeLeft(targetFullPath) {
const targetIndex = tabList.value.findIndex((t) => t.fullPath === targetFullPath);
if (targetIndex > -1) {
@@ -175,7 +147,6 @@ export const useTabsStore = defineTabsStore('tabs', () => {
tabList.value = tabList.value.filter((t, index) =>
t.fullPath === defaultDashboardPath.value || index >= targetIndex
);
// 如果关闭的tab中包含了当前激活的tab,则激活目标tab
if (!tabList.value.find(t => t.fullPath === activeTab.value)) {
activeTab.value = targetFullPath;
}
@@ -184,7 +155,6 @@ export const useTabsStore = defineTabsStore('tabs', () => {
}
}
// 关闭右侧(关闭指定tab右侧的所有tab,保留默认仪表盘和目标tab)
function closeRight(targetFullPath) {
const targetIndex = tabList.value.findIndex((t) => t.fullPath === targetFullPath);
if (targetIndex > -1) {
@@ -195,7 +165,6 @@ export const useTabsStore = defineTabsStore('tabs', () => {
tabList.value = tabList.value.filter((t, index) =>
t.fullPath === defaultDashboardPath.value || index <= targetIndex
);
// 如果关闭的tab中包含了当前激活的tab,则激活目标tab
if (!tabList.value.find(t => t.fullPath === activeTab.value)) {
activeTab.value = targetFullPath;
}
@@ -204,7 +173,6 @@ export const useTabsStore = defineTabsStore('tabs', () => {
}
}
// 关闭全部,只留默认仪表盘
function closeAll() {
const target = defaultDashboardPath.value || activeTab.value;
tabList.value = target
@@ -214,18 +182,15 @@ export const useTabsStore = defineTabsStore('tabs', () => {
saveTabsToStorage(tabList.value, activeTab.value);
}
// 设置激活tab(不触发路由跳转,仅用于更新状态)
function setActiveTab(fullPath) {
activeTab.value = fullPath;
saveTabsToStorage(tabList.value, activeTab.value);
}
// 重置 tabs store 到初始状态(登出时使用)
function resetTabs() {
tabList.value = [];
activeTab.value = '';
defaultDashboardPath.value = '';
// 清除 localStorage 中的 tabs 数据
localStorage.removeItem('tabs_list');
localStorage.removeItem('active_tab');
}
@@ -247,5 +212,4 @@ export const useTabsStore = defineTabsStore('tabs', () => {
};
});
// ========== 菜单 Menu Store ==========
export { useMenuStore } from './menu';
-48
View File
@@ -1,10 +1,7 @@
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
// import { getUserInfo } from '@/utils/auth'
import { getMenus } from '@/api/menu';
// 是否属于「登录态失效」类错误。
// request.js 已给鉴权错误打上 status=401,同时兼容历史文案与 axios 原始错误。
const isAuthError = (err) =>
err?.status === 401 ||
err?.response?.status === 401 ||
@@ -12,21 +9,14 @@ const isAuthError = (err) =>
/token已过期|token无效|无效的token/.test(err?.message || '');
export const useMenuStore = defineStore('menu', () => {
// 菜单数据
const menus = ref([]);
// 加载状态
const loading = ref(false);
// 加载错误
const error = ref(null);
// 正在加载的 Promise(用于避免重复请求)
let loadingPromise = null;
// 菜单缓存 key(基于用户类型、当前企业与角色ID)
// 必须带 tid:菜单是按企业下发的,key 里没有企业会让「切换企业」后
// 直接复用上一家的菜单,导致新企业未开通的模块仍能进入。
const getCacheKey = () => {
try {
const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
@@ -39,14 +29,12 @@ export const useMenuStore = defineStore('menu', () => {
}
};
// 从缓存加载菜单
const loadFromCache = () => {
try {
const cacheKey = getCacheKey();
const cached = localStorage.getItem(cacheKey);
if (cached) {
const menuData = JSON.parse(cached);
// 检查缓存是否过期(5分钟过期)
if (menuData.timestamp && Date.now() - menuData.timestamp < 5 * 60 * 1000) {
return menuData.menus;
}
@@ -57,7 +45,6 @@ export const useMenuStore = defineStore('menu', () => {
return null;
};
// 保存菜单到缓存
const saveToCache = (menuData) => {
try {
const cacheKey = getCacheKey();
@@ -70,19 +57,16 @@ export const useMenuStore = defineStore('menu', () => {
}
};
// 清除菜单缓存
const clearCache = () => {
try {
const cacheKey = getCacheKey();
localStorage.removeItem(cacheKey);
// 也清除其他可能的缓存key(兼容旧代码)
localStorage.removeItem('menu_cache');
} catch (e) {
console.warn('清除菜单缓存失败:', e);
}
};
// 获取用户信息
const getUserInfo = () => {
try {
return JSON.parse(localStorage.getItem('userInfo') || '{}');
@@ -91,14 +75,11 @@ export const useMenuStore = defineStore('menu', () => {
}
};
// 从 API 加载菜单(核心方法,确保只请求一次)
const fetchMenus = async (forceRefresh = false) => {
// 如果已经有正在加载的请求,直接返回该 Promise
if (loadingPromise && !forceRefresh) {
return loadingPromise;
}
// 如果不强制刷新,先尝试从缓存加载
if (!forceRefresh) {
const cachedMenus = loadFromCache();
if (cachedMenus && cachedMenus.length > 0) {
@@ -107,12 +88,10 @@ export const useMenuStore = defineStore('menu', () => {
}
}
// 如果正在加载且不是强制刷新,返回现有的 Promise
if (loading.value && !forceRefresh) {
return loadingPromise;
}
// 创建新的加载 Promise
loadingPromise = (async () => {
loading.value = true;
error.value = null;
@@ -124,39 +103,28 @@ export const useMenuStore = defineStore('menu', () => {
let res;
// 检查用户ID是否存在
if (!userInfo.id) {
throw new Error('用户ID不存在,请重新登录');
}
// 用户登录,使用 getMenus 接口
res = await getMenus(userInfo.id);
// 检查响应格式:HTTP 200 但 body 为空(后端/网关异常)会走到这里,
// 打印原始值便于区分「服务挂了」和「返回了空内容」
if (!res) {
console.error('菜单接口返回空响应:', { res, url: `/backend/menu/${userInfo.id}` });
throw new Error('获取菜单失败:接口返回空响应(后端服务或网关异常)');
}
// 检查后端返回的 code 字段
if (res.code !== 200) {
throw new Error(res.msg || '获取菜单失败');
}
// 如果 code 为 200,检查 data
if (res.code === 200) {
// data 可能是空数组,这也是有效的
if (res.data !== undefined && res.data !== null) {
// 确保 data 是数组
const menuData = Array.isArray(res.data) ? res.data : [];
// 直接使用后端返回的树形结构数据,不需要额外过滤
menus.value = menuData;
// 保存到缓存
saveToCache(menuData);
return menuData;
} else {
// data 为 null 或 undefined,使用空数组
console.warn('菜单数据为空,使用空数组');
menus.value = [];
saveToCache([]);
@@ -164,7 +132,6 @@ export const useMenuStore = defineStore('menu', () => {
}
}
// 如果响应格式不符合预期,尝试直接使用 res.data
if (res.data !== undefined) {
const menuData = Array.isArray(res.data) ? res.data : [];
const filtered = menuData.filter(m => (m.isShow ?? 1) !== 0);
@@ -173,15 +140,10 @@ export const useMenuStore = defineStore('menu', () => {
return filtered;
}
// 如果都不符合,抛出错误
throw new Error(res.message || '获取菜单失败:响应格式错误');
} catch (err) {
error.value = err.message || '获取菜单失败';
// 鉴权失败(令牌过期/无效、会话被吊销):清掉缓存并继续抛出,
// 由 request.js 静默续期或跳认证中心。
// 不能回退到缓存:否则令牌过期时会用旧菜单把登录态问题掩盖掉,
// 用户看到的是一份已经失效的权限菜单。
if (isAuthError(err)) {
clearCache();
menus.value = [];
@@ -196,7 +158,6 @@ export const useMenuStore = defineStore('menu', () => {
stack: err.stack
});
// 如果出错,尝试使用缓存数据
const cachedMenus = loadFromCache();
if (cachedMenus && cachedMenus.length > 0) {
console.warn('使用缓存的菜单数据');
@@ -204,7 +165,6 @@ export const useMenuStore = defineStore('menu', () => {
return cachedMenus;
}
// 如果连缓存都没有,设置空数组,避免页面崩溃
menus.value = [];
throw err;
} finally {
@@ -216,14 +176,10 @@ export const useMenuStore = defineStore('menu', () => {
return loadingPromise;
};
// 刷新菜单(强制从 API 获取)
// 不预先清缓存:接口异常时 fetchMenus 还能回退到上一份菜单,避免整个应用没菜单可用;
// 请求成功后 saveToCache 会直接覆盖旧缓存。
const refreshMenus = async () => {
return await fetchMenus(true);
};
// 重置菜单 store(登出时使用)
const resetMenus = () => {
menus.value = [];
loading.value = false;
@@ -232,20 +188,16 @@ export const useMenuStore = defineStore('menu', () => {
clearCache();
};
// 计算属性:获取菜单列表
const menuList = computed(() => menus.value);
// 计算属性:菜单是否已加载
const isLoaded = computed(() => menus.value.length > 0);
return {
// 状态
menus: menuList,
loading,
error,
isLoaded,
// 方法
fetchMenus,
refreshMenus,
resetMenus,