Compare commits

...

8 Commits

Author SHA1 Message Date
xiaoxian521
f14077bc6f release: update 3.6.0 2022-10-25 17:51:21 +08:00
xiaoxian521
1003a31b4d chore: update 2022-10-22 11:55:15 +08:00
xiaoxian521
cc8a07d25b chore: update @pureadmin/utils latest 2022-10-19 17:08:05 +08:00
xiaoxian521
24db509381 chore: 同步完整版 2022-10-19 14:09:42 +08:00
xiaoxian521
43069ac127 chore: update extensions.json 2022-09-13 17:56:41 +08:00
xiaoxian521
f7ba97c73e chore: 优化样式 2022-09-11 19:54:00 +08:00
xiaoxian521
ee65ec9f72 perf: 使用/** */替换//注释,对编辑器的智能提示更友好 2022-09-11 16:46:21 +08:00
xiaoxian521
230af57c3e perf: 从tailwind.css中移除不常用的@apply 2022-09-11 11:35:13 +08:00
70 changed files with 1678 additions and 1707 deletions

View File

@@ -1,5 +1,6 @@
{
"recommendations": [
"christian-kohler.path-intellisense",
"vscode-icons-team.vscode-icons",
"davidanson.vscode-markdownlint",
"stylelint.vscode-stylelint",
@@ -7,6 +8,8 @@
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"lokalise.i18n-ally",
"redhat.vscode-yaml",
"csstools.postcss",
"mikestead.dotenv",
"eamodio.gitlens",
"antfu.iconify",

View File

@@ -1,6 +1,6 @@
// 处理环境变量
/** 处理环境变量 */
const warpperEnv = (envConf: Recordable): ViteEnv => {
// 此处为默认值,无需修改
/** 此处为默认值,无需修改 */
const ret: ViteEnv = {
VITE_PORT: 8848,
VITE_PUBLIC_PATH: "",
@@ -28,12 +28,12 @@ const warpperEnv = (envConf: Recordable): ViteEnv => {
return ret;
};
// 跨域代理重写
/** 跨域代理重写 */
const regExps = (value: string, reg: string): string => {
return value.replace(new RegExp(`^${reg}`, "g"), "");
};
// 环境变量
/** 环境变量 */
const loadEnv = (): ViteEnv => {
return import.meta.env;
};

View File

@@ -36,9 +36,7 @@
border-radius: 50%;
width: 2.5em;
height: 2.5em;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
-webkit-animation: loadAnimation 1.8s infinite ease-in-out;
animation: loadAnimation 1.8s infinite ease-in-out;
}
@@ -48,10 +46,7 @@
margin: 80px auto;
position: relative;
text-indent: -9999em;
-webkit-transform: translateZ(0);
-ms-transform: translateZ(0);
transform: translateZ(0);
-webkit-animation-delay: -0.16s;
animation-delay: -0.16s;
top: 0;
transform: translate(-50%, 0);
@@ -66,7 +61,6 @@
.loader:before {
left: -3.5em;
-webkit-animation-delay: -0.32s;
animation-delay: -0.32s;
}
@@ -74,18 +68,6 @@
left: 3.5em;
}
@-webkit-keyframes loadAnimation {
0%,
80%,
100% {
box-shadow: 0 2.5em 0 -1.3em;
}
40% {
box-shadow: 0 2.5em 0 0;
}
}
@keyframes loadAnimation {
0%,
80%,

View File

@@ -18,10 +18,14 @@ buttons:
hscloseRightTabs: Close RightTabs
hscloseOtherTabs: Close OtherTabs
hscloseAllTabs: Close AllTabs
hswholeFullScreen: Whole FullScreen
hswholeExitFullScreen: Whole ExitFullScreen
hscontentFullScreen: Content FullScreen
hscontentExitFullScreen: Content ExitFullScreen
menus:
hshome: Home
hslogin: Login
hserror: Error Page
hsabnormal: Abnormal Page
hsfourZeroFour: "404"
hsfourZeroOne: "403"
hsFive: "500"

View File

@@ -18,10 +18,14 @@ buttons:
hscloseRightTabs: 关闭右侧标签页
hscloseOtherTabs: 关闭其他标签页
hscloseAllTabs: 关闭全部标签页
hswholeFullScreen: 整体页面全屏
hswholeExitFullScreen: 整体页面退出全屏
hscontentFullScreen: 内容区全屏
hscontentExitFullScreen: 内容区退出全屏
menus:
hshome: 首页
hslogin: 登录
hserror: 错误页面
hsabnormal: 异常页面
hsfourZeroFour: "404"
hsfourZeroOne: "403"
hsFive: "500"

View File

@@ -1,18 +1,25 @@
// 根据角色动态生成路由
// 模拟后端动态生成路由
import { MockMethod } from "vite-plugin-mock";
/**
* roles页面级别权限这里模拟二种 "admin"、"common"
* admin管理员角色
* common普通角色
*/
const permissionRouter = {
path: "/permission",
meta: {
title: "menus.permission",
icon: "lollipop",
rank: 7
rank: 10
},
children: [
{
path: "/permission/page/index",
name: "PermissionPage",
meta: {
roles: ["admin", "common"],
title: "menus.permissionPage"
}
},
@@ -21,34 +28,22 @@ const permissionRouter = {
name: "PermissionButton",
meta: {
title: "menus.permissionButton",
authority: []
roles: ["admin", "common"],
auths: ["btn_add", "btn_edit", "btn_delete"]
}
}
]
};
// 添加不同按钮权限到/permission/button页面中
function setDifAuthority(authority, routes) {
routes.children[1].meta.authority = [authority];
return routes;
}
export default [
{
url: "/getAsyncRoutes",
method: "get",
response: ({ query }) => {
if (query.name === "admin") {
response: () => {
return {
code: 0,
info: [setDifAuthority("v-admin", permissionRouter)]
success: true,
data: [permissionRouter]
};
} else {
return {
code: 0,
info: [setDifAuthority("v-test", permissionRouter)]
};
}
}
}
] as MockMethod[];

36
mock/login.ts Normal file
View File

@@ -0,0 +1,36 @@
// 根据角色动态生成路由
import { MockMethod } from "vite-plugin-mock";
export default [
{
url: "/login",
method: "post",
response: ({ body }) => {
if (body.username === "admin") {
return {
success: true,
data: {
username: "admin",
// 一个用户可能有多个角色
roles: ["admin"],
accessToken: "eyJhbGciOiJIUzUxMiJ9.admin",
refreshToken: "eyJhbGciOiJIUzUxMiJ9.adminRefresh",
expires: "2023/10/30 00:00:00"
}
};
} else {
return {
success: true,
data: {
username: "common",
// 一个用户可能有多个角色
roles: ["common"],
accessToken: "eyJhbGciOiJIUzUxMiJ9.common",
refreshToken: "eyJhbGciOiJIUzUxMiJ9.commonRefresh",
expires: "2023/10/30 00:00:00"
}
};
}
}
}
] as MockMethod[];

27
mock/refreshToken.ts Normal file
View File

@@ -0,0 +1,27 @@
import { MockMethod } from "vite-plugin-mock";
// 模拟刷新token接口
export default [
{
url: "/refreshToken",
method: "post",
response: ({ body }) => {
if (body.refreshToken) {
return {
success: true,
data: {
accessToken: "eyJhbGciOiJIUzUxMiJ9.admin",
refreshToken: "eyJhbGciOiJIUzUxMiJ9.adminRefresh",
// `expires`选择这种日期格式是为了方便调试,后端直接设置时间戳或许更方便(每次都应该递增)。如果后端返回的是时间戳格式,前端开发请来到这个目录`src/utils/auth.ts`,把第`38`行的代码换成expires = data.expires即可。
expires: "2023/10/30 23:59:59"
}
};
} else {
return {
success: false,
data: {}
};
}
}
}
] as MockMethod[];

View File

@@ -1,6 +1,6 @@
{
"name": "pure-admin-thin",
"version": "3.5.0",
"version": "3.6.0",
"private": true,
"scripts": {
"dev": "NODE_OPTIONS=--max-old-space-size=4096 vite",
@@ -32,8 +32,8 @@
"@pureadmin/components": "^1.1.0",
"@pureadmin/descriptions": "^1.1.0",
"@pureadmin/table": "^1.2.0",
"@pureadmin/utils": "^0.1.1",
"@vueuse/core": "^9.1.1",
"@pureadmin/utils": "^1.1.5",
"@vueuse/core": "^9.3.0",
"@vueuse/motion": "^2.0.0-beta.12",
"@vueuse/shared": "^9.1.1",
"animate.css": "^4.1.1",
@@ -54,7 +54,7 @@
"qs": "^6.11.0",
"resize-observer-polyfill": "^1.5.1",
"responsive-storage": "^2.1.0",
"vue": "^3.2.39",
"vue": "^3.2.40",
"vue-i18n": "^9.2.2",
"vue-router": "^4.1.5",
"vue-types": "^4.2.1",
@@ -67,7 +67,7 @@
"@iconify-icons/ep": "^1.2.7",
"@iconify-icons/ri": "^1.2.3",
"@iconify/vue": "^3.2.1",
"@intlify/vite-plugin-vue-i18n": "^6.0.1",
"@intlify/vite-plugin-vue-i18n": "^6.0.3",
"@pureadmin/theme": "^2.4.0",
"@types/element-resize-detector": "1.1.3",
"@types/js-cookie": "^3.0.1",
@@ -76,17 +76,16 @@
"@types/mockjs": "1.0.3",
"@types/node": "14.14.14",
"@types/nprogress": "0.2.0",
"@types/qrcode": "^1.5.0",
"@types/qs": "^6.9.7",
"@typescript-eslint/eslint-plugin": "^5.10.2",
"@typescript-eslint/parser": "^5.10.2",
"@vitejs/plugin-legacy": "^2.1.0",
"@vitejs/plugin-vue": "^3.1.0",
"@vitejs/plugin-legacy": "^2.2.0",
"@vitejs/plugin-vue": "^3.1.2",
"@vitejs/plugin-vue-jsx": "^2.0.1",
"@vue/eslint-config-prettier": "^7.0.0",
"@vue/eslint-config-typescript": "^10.0.0",
"@vue/runtime-core": "^3.2.39",
"autoprefixer": "^10.4.8",
"@vue/runtime-core": "^3.2.40",
"autoprefixer": "^10.4.12",
"cloc": "^2.10.0",
"cssnano": "^5.1.13",
"eslint": "^8.8.0",
@@ -96,14 +95,14 @@
"husky": "^7.0.4",
"lint-staged": "11.1.2",
"picocolors": "^1.0.0",
"postcss": "^8.4.16",
"postcss": "^8.4.17",
"postcss-html": "^1.5.0",
"postcss-import": "^15.0.0",
"postcss-scss": "^4.0.4",
"postcss-scss": "^4.0.5",
"prettier": "^2.5.1",
"pretty-quick": "3.1.1",
"rimraf": "3.0.2",
"rollup-plugin-visualizer": "^5.8.1",
"rollup-plugin-visualizer": "^5.8.2",
"sass": "^1.53.0",
"sass-loader": "^13.0.2",
"stylelint": "^14.3.0",
@@ -116,12 +115,12 @@
"terser": "^5.15.0",
"typescript": "^4.7.4",
"unplugin-vue-define-options": "0.7.3",
"vite": "^3.1.0",
"vite": "^3.1.8",
"vite-plugin-mock": "^2.9.6",
"vite-plugin-remove-console": "^1.1.0",
"vite-svg-loader": "^3.4.0",
"vite-svg-loader": "^3.6.0",
"vue-eslint-parser": "^8.2.0",
"vue-tsc": "^0.40.7"
"vue-tsc": "^0.40.13"
},
"pnpm": {
"peerDependencyRules": {

1700
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
{
"Version": "3.5.0",
"Version": "3.6.0",
"Title": "PureAdmin",
"FixedHeader": true,
"HiddenSideBar": false,

View File

@@ -1,10 +1,10 @@
import { http } from "../utils/http";
type Result = {
code: number;
info: Array<any>;
success: boolean;
data: Array<any>;
};
export const getAsyncRoutes = (params?: object) => {
return http.request<Result>("get", "/getAsyncRoutes", { params });
export const getAsyncRoutes = () => {
return http.request<Result>("get", "/getAsyncRoutes");
};

View File

@@ -1,26 +1,39 @@
import { http } from "../utils/http";
type Result = {
svg?: string;
code?: number;
info?: object;
export type UserResult = {
success: boolean;
data: {
/** 用户名 */
username: string;
/** 当前登陆用户的角色 */
roles: Array<string>;
/** `token` */
accessToken: string;
/** 用于调用刷新`accessToken`的接口时所需的`token` */
refreshToken: string;
/** `accessToken`的过期时间(格式'xxxx/xx/xx xx:xx:xx' */
expires: Date;
};
};
// 获取验证码
export const getVerify = () => {
return http.request<Result>("get", "/captcha");
export type RefreshTokenResult = {
success: boolean;
data: {
/** `token` */
accessToken: string;
/** 用于调用刷新`accessToken`的接口时所需的`token` */
refreshToken: string;
/** `accessToken`的过期时间(格式'xxxx/xx/xx xx:xx:xx' */
expires: Date;
};
};
// 登录
export const getLogin = (data: object) => {
return http.request("post", "/login", { data });
/** 登录 */
export const getLogin = (data?: object) => {
return http.request<UserResult>("post", "/login", { data });
};
// 刷新token
export const refreshToken = (data: object) => {
return http.request("post", "/refreshToken", { data });
/** 刷新token */
export const refreshTokenApi = (data?: object) => {
return http.request<RefreshTokenResult>("post", "/refreshToken", { data });
};
// export const searchVague = (data: object) => {
// return http.request("post", "/searchVague", { data });
// };

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 36 36"><path d="M19.41 18l8.29-8.29a1 1 0 0 0-1.41-1.41L18 16.59l-8.29-8.3a1 1 0 0 0-1.42 1.42l8.3 8.29l-8.3 8.29A1 1 0 1 0 9.7 27.7l8.3-8.29l8.29 8.29a1 1 0 0 0 1.41-1.41z" fill="currentColor"></path></svg>

Before

Width:  |  Height:  |  Size: 395 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 36 36"><path d="M26 17H10a1 1 0 0 0 0 2h16a1 1 0 0 0 0-2z" fill="currentColor"></path></svg>

Before

Width:  |  Height:  |  Size: 279 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><g fill="none"><path d="M7 12l7 7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path><path d="M7 12l7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path><path d="M21 12H7.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" ></path><path d="M3 3v18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></g></svg>

Before

Width:  |  Height:  |  Size: 647 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 20 20"><path d="M3 5h14V3H3v2zm12 8V7H5v6h10zM3 17h14v-2H3v2z" fill="currentColor"></path></svg>

Before

Width:  |  Height:  |  Size: 284 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><g transform="translate(24 0) scale(-1 1)"><g fill="none"><path d="M7 12l7 7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path><path d="M7 12l7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path><path d="M21 12H7.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path><path d="M3 3v18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></g></g></svg>

Before

Width:  |  Height:  |  Size: 693 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 512 512"><path d="M400 148l-21.12-24.57A191.43 191.43 0 0 0 240 64C134 64 48 150 48 256s86 192 192 192a192.09 192.09 0 0 0 181.07-128" fill="none" stroke="currentColor" stroke-linecap="square" stroke-miterlimit="10" stroke-width="32"></path><path d="M464 68.45V220a4 4 0 0 1-4 4H308.45a4 4 0 0 1-2.83-6.83L457.17 65.62a4 4 0 0 1 6.83 2.83z" fill="currentColor"></path></svg>

Before

Width:  |  Height:  |  Size: 561 B

View File

@@ -0,0 +1,5 @@
import auth from "./src/auth";
const Auth = auth;
export { Auth };

View File

@@ -0,0 +1,20 @@
import { defineComponent, Fragment } from "vue";
import { hasAuth } from "/@/router/utils";
export default defineComponent({
name: "Auth",
props: {
value: {
type: undefined,
default: []
}
},
setup(props, { slots }) {
return () => {
if (!slots) return null;
return hasAuth(props.value) ? (
<Fragment>{slots.default?.()}</Fragment>
) : null;
};
}
});

View File

@@ -4,19 +4,17 @@ import { Icon as IconifyIcon, addIcon } from "@iconify/vue/dist/offline";
// element-plus icon
import Check from "@iconify-icons/ep/check";
import HomeFilled from "@iconify-icons/ep/home-filled";
import Setting from "@iconify-icons/ep/setting";
import Lollipop from "@iconify-icons/ep/lollipop";
import RefreshRight from "@iconify-icons/ep/refresh-right";
import ArrowDown from "@iconify-icons/ep/arrow-down";
import Close from "@iconify-icons/ep/close";
import CloseBold from "@iconify-icons/ep/close-bold";
import Bell from "@iconify-icons/ep/bell";
import Search from "@iconify-icons/ep/search";
addIcon("check", Check);
addIcon("home-filled", HomeFilled);
addIcon("setting", Setting);
addIcon("lollipop", Lollipop);
addIcon("refresh-right", RefreshRight);
addIcon("arrow-down", ArrowDown);
addIcon("close", Close);
addIcon("close-bold", CloseBold);
addIcon("bell", Bell);
addIcon("search", Search);
@@ -33,6 +31,14 @@ import User from "@iconify-icons/ri/user-3-fill";
import Lock from "@iconify-icons/ri/lock-fill";
import MenuUnfold from "@iconify-icons/ri/menu-unfold-fill";
import MenuFold from "@iconify-icons/ri/menu-fold-fill";
import Setting from "@iconify-icons/ri/settings-3-line";
import ArrowDown from "@iconify-icons/ri/arrow-down-s-line";
import CloseLeftTags from "@iconify-icons/ri/text-direction-r";
import CloseRightTags from "@iconify-icons/ri/text-direction-l";
import CloseOtherTags from "@iconify-icons/ri/text-spacing";
import CloseAllTags from "@iconify-icons/ri/subtract-line";
import Fullscreen from "@iconify-icons/ri/fullscreen-fill";
import ExitFullscreen from "@iconify-icons/ri/fullscreen-exit-fill";
addIcon("arrow-right-s-line", ArrowRightSLine);
addIcon("arrow-left-s-line", ArrowLeftSLine);
addIcon("logout-circle-r-line", LogoutCircleRLine);
@@ -44,6 +50,14 @@ addIcon("user", User);
addIcon("lock", Lock);
addIcon("menu-unfold", MenuUnfold);
addIcon("menu-fold", MenuFold);
addIcon("setting", Setting);
addIcon("arrow-down", ArrowDown);
addIcon("close-left-tags", CloseLeftTags);
addIcon("close-right-tags", CloseRightTags);
addIcon("close-other-tags", CloseOtherTags);
addIcon("close-all-tags", CloseAllTags);
addIcon("fullscreen", Fullscreen);
addIcon("exit-fullscreen", ExitFullscreen);
// Iconify Icon在Vue里离线使用用于内网环境https://docs.iconify.design/icon-components/vue/offline.html
export default defineComponent({

View File

@@ -27,7 +27,7 @@ const getConfig = (key?: string): ServerConfigs => {
return config;
};
// 获取项目动态全局配置
/** 获取项目动态全局配置 */
export const getServerConfig = async (app: App): Promise<undefined> => {
app.config.globalProperties.$config = getConfig();
return axios({

View File

@@ -0,0 +1,13 @@
import { hasAuth } from "/@/router/utils";
import { Directive, type DirectiveBinding } from "vue";
export const auth: Directive = {
mounted(el: HTMLElement, binding: DirectiveBinding) {
const { value } = binding;
if (value) {
!hasAuth(value) && el.parentNode.removeChild(el);
} else {
throw new Error("need auths! Like v-auth=\"['btn.add','btn.edit']\"");
}
}
};

View File

@@ -1,7 +1,6 @@
import { Directive, type DirectiveBinding, type VNode } from "vue";
import elementResizeDetectorMaker from "element-resize-detector";
import type { Erd } from "element-resize-detector";
import { optimizeFps } from "@pureadmin/utils";
import { emitter } from "/@/utils/mitt";
const erd: Erd = elementResizeDetectorMaker({
@@ -14,9 +13,7 @@ export const resize: Directive = {
const width = elem.offsetWidth;
const height = elem.offsetHeight;
if (binding?.instance) {
optimizeFps(() => {
emitter.emit("resize", { detail: { width, height } });
})();
} else {
vnode.el.dispatchEvent(
new CustomEvent("resize", { detail: { width, height } })

View File

@@ -1,2 +1,2 @@
export * from "./permission";
export * from "./auth";
export * from "./elResizeDetector";

View File

@@ -1,18 +0,0 @@
import { usePermissionStoreHook } from "/@/store/modules/permission";
import { Directive } from "vue";
import type { DirectiveBinding } from "vue";
export const auth: Directive = {
mounted(el: HTMLElement, binding: DirectiveBinding) {
const { value } = binding;
if (value) {
const authRoles = value;
const hasAuth = usePermissionStoreHook().buttonAuth.includes(authRoles);
if (!hasAuth) {
el.parentNode.removeChild(el);
}
} else {
throw new Error("need roles! Like v-auth=\"['admin','test']\"");
}
}
};

View File

@@ -5,9 +5,7 @@ import mixNav from "./sidebar/mixNav.vue";
import avatars from "/@/assets/avatars.jpg";
import { useNav } from "/@/layout/hooks/useNav";
import Breadcrumb from "./sidebar/breadCrumb.vue";
import { deviceDetection } from "@pureadmin/utils";
import topCollapse from "./sidebar/topCollapse.vue";
import screenfull from "../components/screenfull/index.vue";
import { useTranslationLang } from "../hooks/useTranslationLang";
import globalization from "/@/assets/svg/globalization.svg?component";
@@ -50,8 +48,6 @@ const { t, locale, translationCh, translationEn } = useTranslationLang();
<Search />
<!-- 通知 -->
<Notice id="header-notice" />
<!-- 全屏 -->
<screenfull id="header-screenfull" v-show="!deviceDetection()" />
<!-- 国际化 -->
<el-dropdown id="header-translation" trigger="click">
<globalization
@@ -103,7 +99,7 @@ const { t, locale, translationCh, translationEn } = useTranslationLang();
</template>
</el-dropdown>
<span
class="el-icon-setting navbar-bg-hover"
class="set-icon navbar-bg-hover"
:title="t('buttons.hssystemSet')"
@click="onPanel"
>
@@ -153,15 +149,6 @@ const { t, locale, translationCh, translationEn } = useTranslationLang();
border-radius: 50%;
}
}
.el-icon-setting {
height: 48px;
width: 38px;
padding: 12px;
display: flex;
cursor: pointer;
align-items: center;
}
}
.breadcrumb-container {

View File

@@ -18,13 +18,17 @@ emitter.on("openPanel", () => {
<template>
<div :class="{ show: show }" class="right-panel-container">
<div class="right-panel-background" />
<div ref="target" class="right-panel bg-white dark:bg-dark">
<div ref="target" class="right-panel bg-bg_color">
<div class="right-panel-items">
<div class="project-configuration">
<h3 class="dark:text-white">项目配置</h3>
<el-icon title="关闭配置" class="el-icon-close" @click="show = !show">
<IconifyIconOffline icon="close" />
</el-icon>
<span title="关闭配置">
<IconifyIconOffline
class="dark:text-white"
icon="close"
@click="show = !show"
/>
</span>
</div>
<div
class="border-b-[1px] border-solid border-[#dcdfe6] dark:border-[#303030]"
@@ -121,7 +125,7 @@ emitter.on("openPanel", () => {
top: 15px;
margin-left: 10px;
i {
svg {
font-size: 20px;
margin-right: 20px;

View File

@@ -1,5 +1,6 @@
<script lang="ts" setup>
import { useRouter } from "vue-router";
import { cloneDeep } from "lodash-unified";
import SearchResult from "./SearchResult.vue";
import SearchFooter from "./SearchFooter.vue";
import { useNav } from "/@/layout/hooks/useNav";
@@ -31,7 +32,7 @@ const handleSearch = useDebounceFn(search, 300);
/** 菜单树形结构 */
const menusData = computed(() => {
return deleteChildren(usePermissionStoreHook().menusTree);
return deleteChildren(cloneDeep(usePermissionStoreHook().wholeMenus));
});
const show = computed({

View File

@@ -14,6 +14,7 @@ import panel from "../panel/index.vue";
import { emitter } from "/@/utils/mitt";
import { resetRouter } from "/@/router";
import { templateRef } from "@vueuse/core";
import { removeToken } from "/@/utils/auth";
import { routerArrays } from "/@/layout/types";
import { useNav } from "/@/layout/hooks/useNav";
import { useAppStoreHook } from "/@/store/modules/app";
@@ -131,16 +132,17 @@ const multiTagsCacheChange = () => {
/** 清空缓存并返回登录页 */
function onReset() {
router.push("/login");
removeToken();
storageLocal.clear();
storageSession.clear();
const { Grey, Weak, MultiTagsCache, EpThemeColor, Layout } = getConfig();
useAppStoreHook().setLayout(Layout);
setEpThemeColor(EpThemeColor);
useMultiTagsStoreHook().multiTagsCacheChange(MultiTagsCache);
toggleClass(Grey, "html-grey", document.querySelector("html"));
toggleClass(Weak, "html-weakness", document.querySelector("html"));
router.push("/login");
useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
storageLocal.clear();
storageSession.clear();
resetRouter();
}

View File

@@ -1,12 +1,10 @@
<script setup lang="ts">
import { ref, watch } from "vue";
import Search from "../search/index.vue";
import Notice from "../notice/index.vue";
import { ref, watch, nextTick } from "vue";
import SidebarItem from "./sidebarItem.vue";
import avatars from "/@/assets/avatars.jpg";
import { useNav } from "/@/layout/hooks/useNav";
import screenfull from "../screenfull/index.vue";
import { deviceDetection } from "@pureadmin/utils";
import { useTranslationLang } from "../../hooks/useTranslationLang";
import { usePermissionStoreHook } from "/@/store/modules/permission";
import globalization from "/@/assets/svg/globalization.svg?component";
@@ -28,6 +26,10 @@ const {
getDropdownItemClass
} = useNav();
nextTick(() => {
menuRef.value?.handleResize();
});
watch(
() => route.path,
() => {
@@ -62,8 +64,6 @@ watch(
<Search />
<!-- 通知 -->
<Notice id="header-notice" />
<!-- 全屏 -->
<screenfull id="header-screenfull" v-show="!deviceDetection()" />
<!-- 国际化 -->
<el-dropdown id="header-translation" trigger="click">
<globalization
@@ -113,7 +113,7 @@ watch(
</template>
</el-dropdown>
<span
class="el-icon-setting navbar-bg-hover"
class="set-icon navbar-bg-hover"
:title="t('buttons.hssystemSet')"
@click="onPanel"
>

View File

@@ -51,6 +51,12 @@ const { title } = useNav();
margin-top: 5px;
.sidebar-title {
display: block;
width: 160px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-align: left;
color: #1890ff;
font-weight: 600;
font-size: 20px;

View File

@@ -4,9 +4,7 @@ import Notice from "../notice/index.vue";
import avatars from "/@/assets/avatars.jpg";
import { useNav } from "/@/layout/hooks/useNav";
import { transformI18n } from "/@/plugins/i18n";
import screenfull from "../screenfull/index.vue";
import { deviceDetection } from "@pureadmin/utils";
import { ref, toRaw, watch, onMounted } from "vue";
import { ref, toRaw, watch, onMounted, nextTick } from "vue";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { getParentPaths, findRouteByPath } from "/@/router/utils";
import { useTranslationLang } from "../../hooks/useTranslationLang";
@@ -45,8 +43,12 @@ onMounted(() => {
getDefaultActive(route.path);
});
nextTick(() => {
menuRef.value?.handleResize();
});
watch(
() => route.path,
() => [route.path, usePermissionStoreHook().wholeMenus],
() => {
getDefaultActive(route.path);
}
@@ -94,8 +96,6 @@ watch(
<Search />
<!-- 通知 -->
<Notice id="header-notice" />
<!-- 全屏 -->
<screenfull id="header-screenfull" v-show="!deviceDetection()" />
<!-- 国际化 -->
<el-dropdown id="header-translation" trigger="click">
<globalization
@@ -145,7 +145,7 @@ watch(
</template>
</el-dropdown>
<span
class="el-icon-setting navbar-bg-hover"
class="set-icon navbar-bg-hover"
:title="t('buttons.hssystemSet')"
@click="onPanel"
>

View File

@@ -27,7 +27,7 @@ const menuData = computed(() => {
: usePermissionStoreHook().wholeMenus;
});
function getSubMenuData(path) {
function getSubMenuData(path: string) {
// path的上级路由组成的数组
const parentPathArr = getParentPaths(
path,
@@ -41,6 +41,7 @@ function getSubMenuData(path) {
if (!parenetRoute?.children) return;
subMenuData.value = parenetRoute?.children;
}
getSubMenuData(route.path);
onBeforeMount(() => {
@@ -50,7 +51,7 @@ onBeforeMount(() => {
});
watch(
() => route.path,
() => [route.path, usePermissionStoreHook().wholeMenus],
() => {
getSubMenuData(route.path);
menuSelect(route.path, routers);

View File

@@ -121,21 +121,6 @@
}
}
.right-button {
display: flex;
font-size: 16px;
li {
display: flex;
align-items: center;
justify-content: center;
width: 40px;
height: 38px;
border-right: 1px solid #ccc;
cursor: pointer;
}
}
/* 右键菜单 */
.contextmenu {
margin: 0;
@@ -196,6 +181,9 @@
margin-right: 10px;
}
:deep(.el-dropdown-menu__item--divided) {
margin: 1px 0;
}
.el-dropdown-menu__item--divided::before {
margin: 0;
}
@@ -223,7 +211,8 @@
}
.arrow-left,
.arrow-right {
.arrow-right,
.arrow-down {
width: 40px;
height: 38px;
color: var(--el-text-color-primary);
@@ -248,7 +237,7 @@
.arrow-right {
box-shadow: -5px 0 5px -6px #ccc;
border-right: 1px solid #ccc;
border-right: 0.5px solid #ccc;
&:hover {
cursor: e-resize;
@@ -305,8 +294,3 @@
background: var(--el-color-primary);
animation: scheduleOutWidth 400ms ease-in;
}
/* 刷新按钮动画效果 */
.refresh-button {
animation: rotate 600ms linear infinite;
}

View File

@@ -1,15 +1,15 @@
<script setup lang="ts">
import { $t } from "/@/plugins/i18n";
import { emitter } from "/@/utils/mitt";
import { RouteConfigs } from "../../types";
import { useTags } from "../../hooks/useTag";
import { routerArrays } from "/@/layout/types";
import { isEqual, isEmpty } from "lodash-unified";
import { toggleClass, removeClass } from "@pureadmin/utils";
import { useResizeObserver, useDebounceFn } from "@vueuse/core";
import { useSettingStoreHook } from "/@/store/modules/settings";
import { ref, watch, unref, nextTick, onBeforeMount } from "vue";
import { handleAliveRoute, delAliveRoutes } from "/@/router/utils";
import { useMultiTagsStoreHook } from "/@/store/modules/multiTags";
import { ref, watch, unref, toRaw, nextTick, onBeforeMount } from "vue";
import { useResizeObserver, useDebounceFn, useFullscreen } from "@vueuse/core";
const {
route,
@@ -23,6 +23,7 @@ const {
buttonLeft,
showModel,
translateX,
pureSetting,
activeIndex,
getTabStyle,
iconIsActive,
@@ -34,12 +35,15 @@ const {
onMounted,
onMouseenter,
onMouseleave,
transformI18n
transformI18n,
onContentFullScreen
} = useTags();
const tabDom = ref();
const containerDom = ref();
const scrollbarDom = ref();
let isShowArrow = ref(false);
const { isFullscreen, toggle } = useFullscreen();
const dynamicTagView = () => {
const index = multiTags.value.findIndex(item => {
@@ -66,6 +70,9 @@ const moveToView = (index: number): void => {
: 0;
// 已有标签页总长度(包含溢出部分)
const tabDomWidth = tabDom.value ? tabDom.value?.offsetWidth : 0;
scrollbarDomWidth <= tabDomWidth
? (isShowArrow.value = true)
: (isShowArrow.value = false);
if (tabDomWidth < scrollbarDomWidth || tabItemElOffsetLeft === 0) {
translateX.value = 0;
} else if (tabItemElOffsetLeft < -translateX.value) {
@@ -143,16 +150,11 @@ function dynamicRouteTag(value: string, parentPath: string): void {
/** 刷新路由 */
function onFresh() {
const refreshButton = "refresh-button";
toggleClass(true, refreshButton, document.querySelector(".rotate"));
const { fullPath, query } = unref(route);
router.replace({
path: "/redirect" + fullPath,
query: query
});
setTimeout(() => {
removeClass(document.querySelector(".rotate"), refreshButton);
}, 600);
}
function deleteDynamicTag(obj: any, current: any, tag?: string) {
@@ -277,6 +279,32 @@ function onClickDrop(key, item, selectRoute?: RouteConfigs) {
});
router.push("/welcome");
break;
case 6:
// 整体页面全屏
toggle();
setTimeout(() => {
if (isFullscreen.value) {
tagsViews[6].icon = "exit-fullscreen";
tagsViews[6].text = $t("buttons.hswholeExitFullScreen");
} else {
tagsViews[6].icon = "fullscreen";
tagsViews[6].text = $t("buttons.hswholeFullScreen");
}
}, 100);
break;
case 7:
// 内容区全屏
onContentFullScreen();
setTimeout(() => {
if (pureSetting.hiddenSideBar) {
tagsViews[7].icon = "exit-fullscreen";
tagsViews[7].text = $t("buttons.hscontentExitFullScreen");
} else {
tagsViews[7].icon = "fullscreen";
tagsViews[7].text = $t("buttons.hscontentFullScreen");
}
}, 100);
break;
}
setTimeout(() => {
showMenuModel(route.fullPath, route.query);
@@ -467,9 +495,9 @@ onMounted(() => {
<template>
<div ref="containerDom" class="tags-view" v-if="!showTags">
<div class="arrow-left">
<span v-show="isShowArrow" class="arrow-left">
<IconifyIconOffline icon="arrow-left-s-line" @click="handleScroll(200)" />
</div>
</span>
<div ref="scrollbarDom" class="scroll-container">
<div class="tab" ref="tabDom" :style="getTabStyle">
<div
@@ -512,7 +540,7 @@ onMounted(() => {
</div>
</div>
</div>
<span class="arrow-right">
<span v-show="isShowArrow" class="arrow-right">
<IconifyIconOffline
icon="arrow-right-s-line"
@click="handleScroll(-200)"
@@ -527,35 +555,26 @@ onMounted(() => {
class="contextmenu"
>
<div
v-for="(item, key) in tagsViews"
v-for="(item, key) in tagsViews.slice(0, 6)"
:key="key"
style="display: flex; align-items: center"
>
<li v-if="item.show" @click="selectTag(key, item)">
<component :is="toRaw(item.icon)" :key="key" />
<IconifyIconOffline :icon="item.icon" />
{{ transformI18n(item.text) }}
</li>
</div>
</ul>
</transition>
<!-- 右侧功能按钮 -->
<ul class="right-button">
<li>
<span
:title="transformI18n('buttons.hsrefreshRoute')"
class="el-icon-refresh-right rotate"
@click="onFresh"
>
<IconifyIconOffline icon="refresh-right" />
</span>
</li>
<li>
<el-dropdown
trigger="click"
placement="bottom-end"
@command="handleCommand"
>
<span class="arrow-down">
<IconifyIconOffline icon="arrow-down" class="dark:text-white" />
</span>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item
@@ -565,21 +584,12 @@ onMounted(() => {
:divided="item.divided"
:disabled="item.disabled"
>
<component
:is="toRaw(item.icon)"
:key="key"
style="margin-right: 6px"
/>
<IconifyIconOffline :icon="item.icon" />
{{ transformI18n(item.text) }}
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</li>
<li>
<slot />
</li>
</ul>
</div>
</template>

View File

@@ -1,26 +1,25 @@
import { computed } from "vue";
import { router } from "/@/router";
import { getConfig } from "/@/config";
import { useRouter } from "vue-router";
import { emitter } from "/@/utils/mitt";
import { routeMetaType } from "../types";
import type { StorageConfigs } from "/#/index";
import { routerArrays } from "/@/layout/types";
import { useGlobal } from "@pureadmin/utils";
import { transformI18n } from "/@/plugins/i18n";
import { router, remainingPaths } from "/@/router";
import { useAppStoreHook } from "/@/store/modules/app";
import { remainingPaths, resetRouter } from "/@/router";
import { storageSession, useGlobal } from "@pureadmin/utils";
import { useUserStoreHook } from "/@/store/modules/user";
import { useEpThemeStoreHook } from "/@/store/modules/epTheme";
import { useMultiTagsStoreHook } from "/@/store/modules/multiTags";
const errorInfo = "当前路由配置不正确,请检查配置";
export function useNav() {
const pureApp = useAppStoreHook();
const routers = useRouter().options.routes;
/** 用户名 */
const username: string =
storageSession.getItem<StorageConfigs>("info")?.username;
const username = computed(() => {
return useUserStoreHook()?.username;
});
/** 设置国际化选中后的样式 */
const getDropdownItemStyle = computed(() => {
@@ -39,7 +38,7 @@ export function useNav() {
});
const avatarsStyle = computed(() => {
return username ? { marginRight: "10px" } : "";
return username.value ? { marginRight: "10px" } : "";
});
const isCollapse = computed(() => {
@@ -68,10 +67,7 @@ export function useNav() {
/** 退出登录 */
function logout() {
useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
storageSession.removeItem("info");
router.push("/login");
resetRouter();
useUserStoreHook().logOut();
}
function backHome() {

View File

@@ -14,20 +14,15 @@ import type { StorageConfigs } from "/#/index";
import { useEventListener } from "@vueuse/core";
import { useRoute, useRouter } from "vue-router";
import { transformI18n, $t } from "/@/plugins/i18n";
import { useSettingStoreHook } from "/@/store/modules/settings";
import { useMultiTagsStoreHook } from "/@/store/modules/multiTags";
import { storageLocal, toggleClass, hasClass } from "@pureadmin/utils";
import close from "/@/assets/svg/close.svg?component";
import refresh from "/@/assets/svg/refresh.svg?component";
import closeAll from "/@/assets/svg/close_all.svg?component";
import closeLeft from "/@/assets/svg/close_left.svg?component";
import closeOther from "/@/assets/svg/close_other.svg?component";
import closeRight from "/@/assets/svg/close_right.svg?component";
export function useTags() {
const route = useRoute();
const router = useRouter();
const instance = getCurrentInstance();
const pureSetting = useSettingStoreHook();
const buttonTop = ref(0);
const buttonLeft = ref(0);
@@ -53,46 +48,60 @@ export function useTags() {
const tagsViews = reactive<Array<tagsViewsType>>([
{
icon: refresh,
icon: "refresh-right",
text: $t("buttons.hsreload"),
divided: false,
disabled: false,
show: true
},
{
icon: close,
icon: "close",
text: $t("buttons.hscloseCurrentTab"),
divided: false,
disabled: multiTags.value.length > 1 ? false : true,
show: true
},
{
icon: closeLeft,
icon: "close-left-tags",
text: $t("buttons.hscloseLeftTabs"),
divided: true,
disabled: multiTags.value.length > 1 ? false : true,
show: true
},
{
icon: closeRight,
icon: "close-right-tags",
text: $t("buttons.hscloseRightTabs"),
divided: false,
disabled: multiTags.value.length > 1 ? false : true,
show: true
},
{
icon: closeOther,
icon: "close-other-tags",
text: $t("buttons.hscloseOtherTabs"),
divided: true,
disabled: multiTags.value.length > 2 ? false : true,
show: true
},
{
icon: closeAll,
icon: "close-all-tags",
text: $t("buttons.hscloseAllTabs"),
divided: false,
disabled: multiTags.value.length > 1 ? false : true,
show: true
},
{
icon: "fullscreen",
text: $t("buttons.hswholeFullScreen"),
divided: true,
disabled: false,
show: true
},
{
icon: "fullscreen",
text: $t("buttons.hscontentFullScreen"),
divided: false,
disabled: false,
show: true
}
]);
@@ -172,6 +181,12 @@ export function useTags() {
}
}
function onContentFullScreen() {
pureSetting.hiddenSideBar
? pureSetting.changeSetting({ key: "hiddenSideBar", value: false })
: pureSetting.changeSetting({ key: "hiddenSideBar", value: true });
}
onMounted(() => {
if (!showModel.value) {
const configure = storageLocal.getItem<StorageConfigs>(
@@ -201,6 +216,7 @@ export function useTags() {
buttonTop,
buttonLeft,
translateX,
pureSetting,
activeIndex,
getTabStyle,
iconIsActive,
@@ -213,6 +229,7 @@ export function useTags() {
onMounted,
onMouseenter,
onMouseleave,
transformI18n
transformI18n,
onContentFullScreen
};
}

View File

@@ -7,16 +7,13 @@ import { useSettingStoreHook } from "/@/store/modules/settings";
import { deviceDetection, useDark, useGlobal } from "@pureadmin/utils";
import { h, reactive, computed, onMounted, defineComponent } from "vue";
import backTop from "/@/assets/svg/back_top.svg?component";
import fullScreen from "/@/assets/svg/full_screen.svg?component";
import exitScreen from "/@/assets/svg/exit_screen.svg?component";
import navbar from "./components/navbar.vue";
import tag from "./components/tag/index.vue";
import appMain from "./components/appMain.vue";
import setting from "./components/setting/index.vue";
import Vertical from "./components/sidebar/vertical.vue";
import Horizontal from "./components/sidebar/horizontal.vue";
import backTop from "/@/assets/svg/back_top.svg?component";
const { isDark } = useDark();
const { layout } = useLayout();
@@ -102,12 +99,6 @@ onMounted(() => {
}
});
function onFullScreen() {
pureSetting.hiddenSideBar
? pureSetting.changeSetting({ key: "hiddenSideBar", value: false })
: pureSetting.changeSetting({ key: "hiddenSideBar", value: true });
}
const layoutHeader = defineComponent({
render() {
return h(
@@ -127,31 +118,11 @@ const layoutHeader = defineComponent({
!pureSetting.hiddenSideBar &&
(layout.value.includes("vertical") || layout.value.includes("mix"))
? h(navbar)
: h("div"),
: null,
!pureSetting.hiddenSideBar && layout.value.includes("horizontal")
? h(Horizontal)
: h("div"),
h(
tag,
{},
{
default: () => [
h(
"span",
{
onClick: onFullScreen
},
{
default: () => [
!pureSetting.hiddenSideBar
? h(fullScreen, { class: "dark:text-white" })
: h(exitScreen, { class: "dark:text-white" })
]
}
)
]
}
)
: null,
h(tag)
]
}
);
@@ -226,10 +197,6 @@ const layoutHeader = defineComponent({
}
}
.main-hidden {
margin-left: 0 !important;
}
.app-mask {
background: #000;
opacity: 0.3;

View File

@@ -1,4 +1,3 @@
import { Component } from "vue";
export const routerArrays: Array<RouteConfigs> = [
{
path: "/welcome",
@@ -15,7 +14,7 @@ export type routeMetaType = {
icon?: string;
showLink?: boolean;
savedPosition?: boolean;
authority?: Array<string>;
auths?: Array<string>;
};
export type RouteConfigs = {
@@ -33,7 +32,7 @@ export type multiTagsType = {
};
export type tagsViewsType = {
icon: Component;
icon: string;
text: string;
divided: boolean;
disabled: boolean;

View File

@@ -44,6 +44,10 @@ app.component("IconifyIconOffline", IconifyIconOffline);
app.component("IconifyIconOnline", IconifyIconOnline);
app.component("FontIcon", FontIcon);
// 全局注册按钮级别权限组件
import { Auth } from "/@/components/ReAuth";
app.component("Auth", Auth);
getServerConfig(app).then(async config => {
app.use(router);
await router.isReady();

View File

@@ -58,7 +58,7 @@ export function transformI18n(message: any = "") {
}
}
// 此函数只是配合i18n Ally插件来进行国际化智能提示并无实际意义只对提示起作用如果不需要国际化可删除
/** 此函数只是配合i18n Ally插件来进行国际化智能提示并无实际意义只对提示起作用如果不需要国际化可删除 */
export const $t = (key: string) => key;
export const i18n: I18n = createI18n({

View File

@@ -2,8 +2,8 @@ import { getConfig } from "/@/config";
import { toRouteType } from "./types";
import NProgress from "/@/utils/progress";
import { findIndex } from "lodash-unified";
import type { StorageConfigs } from "/#/index";
import { transformI18n } from "/@/plugins/i18n";
import { sessionKey, type DataInfo } from "/@/utils/auth";
import { useMultiTagsStoreHook } from "/@/store/modules/multiTags";
import { usePermissionStoreHook } from "/@/store/modules/permission";
import {
@@ -15,6 +15,7 @@ import {
import {
ascending,
initRouter,
isOneOfArray,
getHistoryMode,
findRouteByPath,
handleAliveRoute,
@@ -32,25 +33,25 @@ import homeRouter from "./modules/home";
import errorRouter from "./modules/error";
import remainingRouter from "./modules/remaining";
// 原始静态路由(未做任何处理)
/** 原始静态路由(未做任何处理) */
const routes = [homeRouter, errorRouter];
// 导出处理后的静态路由(三级及以上的路由全部拍成二级)
/** 导出处理后的静态路由(三级及以上的路由全部拍成二级) */
export const constantRoutes: Array<RouteRecordRaw> = formatTwoStageRoutes(
formatFlatteningRoutes(buildHierarchyTree(ascending(routes)))
);
// 用于渲染菜单,保持原始层级
/** 用于渲染菜单,保持原始层级 */
export const constantMenus: Array<RouteComponent> = ascending(routes).concat(
...remainingRouter
);
// 不参与菜单的路由
/** 不参与菜单的路由 */
export const remainingPaths = Object.keys(remainingRouter).map(v => {
return remainingRouter[v].path;
});
// 创建路由实例
/** 创建路由实例 */
export const router: Router = createRouter({
history: getHistoryMode(),
routes: constantRoutes.concat(...(remainingRouter as any)),
@@ -70,7 +71,7 @@ export const router: Router = createRouter({
}
});
// 重置路由
/** 重置路由 */
export function resetRouter() {
router.getRoutes().forEach(route => {
const { name, meta } = route;
@@ -84,7 +85,7 @@ export function resetRouter() {
usePermissionStoreHook().clearAllCachePage();
}
// 路由白名单
/** 路由白名单 */
const whiteList = ["/login"];
router.beforeEach((to: toRouteType, _from, next) => {
@@ -96,10 +97,10 @@ router.beforeEach((to: toRouteType, _from, next) => {
handleAliveRoute(newMatched);
}
}
const name = storageSession.getItem<StorageConfigs>("info");
const userInfo = storageSession.getItem<DataInfo<number>>(sessionKey);
NProgress.start();
const externalLink = isUrl(to?.name as string);
if (!externalLink)
if (!externalLink) {
to.matched.some(item => {
if (!item.meta.title) return "";
const Title = getConfig().Title;
@@ -107,7 +108,12 @@ router.beforeEach((to: toRouteType, _from, next) => {
document.title = `${transformI18n(item.meta.title)} | ${Title}`;
else document.title = transformI18n(item.meta.title);
});
if (name) {
}
if (userInfo) {
// 无权限跳转403页面
if (to.meta?.roles && !isOneOfArray(to.meta?.roles, userInfo?.roles)) {
next({ path: "/error/403" });
}
if (_from?.name) {
// name为超链接
if (externalLink) {
@@ -118,8 +124,11 @@ router.beforeEach((to: toRouteType, _from, next) => {
}
} else {
// 刷新
if (usePermissionStoreHook().wholeMenus.length === 0)
initRouter(name.username).then((router: Router) => {
if (
usePermissionStoreHook().wholeMenus.length === 0 &&
to.path !== "/login"
)
initRouter().then((router: Router) => {
if (!useMultiTagsStoreHook().getMultiTagsCache) {
const { path } = to;
const index = findIndex(remainingRouter, v => {

View File

@@ -6,7 +6,7 @@ const errorRouter: RouteConfigsTable = {
redirect: "/error/403",
meta: {
icon: "information-line",
title: $t("menus.hserror"),
title: $t("menus.hsabnormal"),
rank: 9
},
children: [

View File

@@ -2,6 +2,7 @@ import { RouteLocationNormalized } from "vue-router";
export interface toRouteType extends RouteLocationNormalized {
meta: {
roles: Array<string>;
keepAlive?: boolean;
dynamicLevel?: string;
};

View File

@@ -9,10 +9,16 @@ import {
import { router } from "./index";
import { isProxy, toRaw } from "vue";
import { loadEnv } from "../../build";
import { cloneDeep } from "lodash-unified";
import { useTimeoutFn } from "@vueuse/core";
import { RouteConfigs } from "/@/layout/types";
import { buildHierarchyTree } from "@pureadmin/utils";
import {
isString,
storageSession,
buildHierarchyTree,
isIncludeAllChildren
} from "@pureadmin/utils";
import { cloneDeep, intersection } from "lodash-unified";
import { sessionKey, type DataInfo } from "/@/utils/auth";
import { usePermissionStoreHook } from "/@/store/modules/permission";
const IFrame = () => import("/@/layout/frameView.vue");
// https://cn.vitejs.dev/guide/features.html#glob-import
@@ -21,7 +27,7 @@ const modulesRoutes = import.meta.glob("/src/views/**/*.{vue,tsx}");
// 动态路由
import { getAsyncRoutes } from "/@/api/routes";
// 按照路由中meta下的rank等级升序来排序路由
/** 按照路由中meta下的rank等级升序来排序路由 */
function ascending(arr: any[]) {
arr.forEach(v => {
if (v?.meta?.rank === null) v.meta.rank = undefined;
@@ -38,7 +44,7 @@ function ascending(arr: any[]) {
);
}
// 过滤meta中showLink为false的路由
/** 过滤meta中showLink为false的菜单 */
function filterTree(data: RouteComponent[]) {
const newTree = cloneDeep(data).filter(
(v: { meta: { showLink: boolean } }) => v.meta?.showLink !== false
@@ -49,7 +55,38 @@ function filterTree(data: RouteComponent[]) {
return newTree;
}
// 批量删除缓存路由(keepalive)
/** 过滤children长度为0的的目录当目录下没有菜单时会过滤此目录目录没有赋予roles权限当目录下只要有一个菜单有显示权限那么此目录就会显示 */
function filterChildrenTree(data: RouteComponent[]) {
const newTree = cloneDeep(data).filter((v: any) => v?.children?.length !== 0);
newTree.forEach(
(v: { children }) => v.children && (v.children = filterTree(v.children))
);
return newTree;
}
/** 判断两个数组彼此是否存在相同值 */
function isOneOfArray(a: Array<string>, b: Array<string>) {
return Array.isArray(a) && Array.isArray(b)
? intersection(a, b).length > 0
? true
: false
: true;
}
/** 从sessionStorage里取出当前登陆用户的角色roles过滤无权限的菜单 */
function filterNoPermissionTree(data: RouteComponent[]) {
const currentRoles =
storageSession.getItem<DataInfo<number>>(sessionKey).roles ?? [];
const newTree = cloneDeep(data).filter((v: any) =>
isOneOfArray(v.meta?.roles, currentRoles)
);
newTree.forEach(
(v: any) => v.children && (v.children = filterNoPermissionTree(v.children))
);
return filterChildrenTree(newTree);
}
/** 批量删除缓存路由(keepalive) */
function delAliveRoutes(delAliveRouteList: Array<RouteConfigs>) {
delAliveRouteList.forEach(route => {
usePermissionStoreHook().cacheOperate({
@@ -59,7 +96,7 @@ function delAliveRoutes(delAliveRouteList: Array<RouteConfigs>) {
});
}
// 通过path获取父级路径
/** 通过path获取父级路径 */
function getParentPaths(path: string, routes: RouteRecordRaw[]) {
// 深度遍历查找
function dfs(routes: RouteRecordRaw[], path: string, parents: string[]) {
@@ -83,7 +120,7 @@ function getParentPaths(path: string, routes: RouteRecordRaw[]) {
return dfs(routes, path, []);
}
// 查找对应path的路由信息
/** 查找对应path的路由信息 */
function findRouteByPath(path: string, routes: RouteRecordRaw[]) {
let res = routes.find((item: { path: string }) => item.path == path);
if (res) {
@@ -114,14 +151,15 @@ function addPathMatch() {
}
}
// 初始化路由
function initRouter(name: string) {
/** 初始化路由 */
function initRouter() {
return new Promise(resolve => {
getAsyncRoutes({ name }).then(({ info }) => {
if (info.length === 0) {
usePermissionStoreHook().changeSetting(info);
getAsyncRoutes().then(({ data }) => {
if (data.length === 0) {
usePermissionStoreHook().handleWholeMenus(data);
resolve(router);
} else {
formatFlatteningRoutes(addAsyncRoutes(info)).map(
formatFlatteningRoutes(addAsyncRoutes(data)).map(
(v: RouteRecordRaw) => {
// 防止重复添加路由
if (
@@ -144,7 +182,7 @@ function initRouter(name: string) {
resolve(router);
}
);
usePermissionStoreHook().changeSetting(info);
usePermissionStoreHook().handleWholeMenus(data);
}
addPathMatch();
});
@@ -195,7 +233,7 @@ function formatTwoStageRoutes(routesList: RouteRecordRaw[]) {
return newRoutesList;
}
// 处理缓存路由(添加、删除、刷新)
/** 处理缓存路由(添加、删除、刷新) */
function handleAliveRoute(matched: RouteRecordNormalized[], mode?: string) {
switch (mode) {
case "add":
@@ -222,7 +260,7 @@ function handleAliveRoute(matched: RouteRecordNormalized[], mode?: string) {
}
}
// 过滤后端传来的动态路由 重新生成规范路由
/** 过滤后端传来的动态路由 重新生成规范路由 */
function addAsyncRoutes(arrRoutes: Array<RouteRecordRaw>) {
if (!arrRoutes || !arrRoutes.length) return;
const modulesRoutesKeys = Object.keys(modulesRoutes);
@@ -251,7 +289,7 @@ function addAsyncRoutes(arrRoutes: Array<RouteRecordRaw>) {
return arrRoutes;
}
// 获取路由历史模式 https://next.router.vuejs.org/zh/guide/essentials/history-mode.html
/** 获取路由历史模式 https://next.router.vuejs.org/zh/guide/essentials/history-mode.html */
function getHistoryMode(): RouterHistory {
const routerHistory = loadEnv().VITE_ROUTER_HISTORY;
// len为1 代表只有历史模式 为2 代表历史模式中存在base参数 https://next.router.vuejs.org/zh/api/#%E5%8F%82%E6%95%B0-1
@@ -275,30 +313,29 @@ function getHistoryMode(): RouterHistory {
}
}
// 是否有权限
function hasPermissions(value: Array<string>): boolean {
if (value && value instanceof Array && value.length > 0) {
const roles = usePermissionStoreHook().buttonAuth;
const permissionRoles = value;
const hasPermission = roles.some(role => {
return permissionRoles.includes(role);
});
if (!hasPermission) {
return false;
}
return true;
} else {
return false;
/** 获取当前页面按钮级别的权限 */
function getAuths(): Array<string> {
return router.currentRoute.value.meta.auths as Array<string>;
}
/** 是否有按钮级别的权限 */
function hasAuth(value: string | Array<string>): boolean {
if (!value) return false;
/** 从当前路由的`meta`字段里获取按钮级别的所有自定义`code`值 */
const metaAuths = getAuths();
const isAuths = isString(value)
? metaAuths.includes(value)
: isIncludeAllChildren(value, metaAuths);
return isAuths ? true : false;
}
export {
hasAuth,
getAuths,
ascending,
filterTree,
initRouter,
hasPermissions,
isOneOfArray,
getHistoryMode,
addAsyncRoutes,
delAliveRoutes,
@@ -306,5 +343,6 @@ export {
findRouteByPath,
handleAliveRoute,
formatTwoStageRoutes,
formatFlatteningRoutes
formatFlatteningRoutes,
filterNoPermissionTree
};

View File

@@ -18,7 +18,7 @@ export const useEpThemeStore = defineStore({
getEpThemeColor() {
return this.epThemeColor;
},
// 用于mix导航模式下hamburger-svg的fill属性
/** 用于mix导航模式下hamburger-svg的fill属性 */
fill() {
if (this.epTheme === "light") {
return "#409eff";
@@ -34,6 +34,7 @@ export const useEpThemeStore = defineStore({
const layout = storageLocal.getItem<StorageConfigs>("responsive-layout");
this.epTheme = layout?.theme;
this.epThemeColor = newColor;
if (!layout) return;
layout.epThemeColor = newColor;
storageLocal.setItem("responsive-layout", layout);
}

View File

@@ -2,9 +2,7 @@ import { defineStore } from "pinia";
import { store } from "/@/store";
import { cacheType } from "./types";
import { constantMenus } from "/@/router";
import { cloneDeep } from "lodash-unified";
import { RouteConfigs } from "/@/layout/types";
import { ascending, filterTree } from "/@/router/utils";
import { ascending, filterTree, filterNoPermissionTree } from "/@/router/utils";
export const usePermissionStore = defineStore({
id: "pure-permission",
@@ -13,40 +11,15 @@ export const usePermissionStore = defineStore({
constantMenus,
// 整体路由生成的菜单(静态、动态)
wholeMenus: [],
// 深拷贝一个菜单树,与导航菜单不突出
menusTree: [],
buttonAuth: [],
// 缓存页面keepAlive
cachePageList: []
}),
actions: {
// 获取异步路由菜单
asyncActionRoutes(routes) {
if (this.wholeMenus.length > 0) return;
this.wholeMenus = filterTree(
ascending(this.constantMenus.concat(routes))
);
this.menusTree = cloneDeep(
/** 组装整体路由生成的菜单 */
handleWholeMenus(routes: any[]) {
this.wholeMenus = filterNoPermissionTree(
filterTree(ascending(this.constantMenus.concat(routes)))
);
const getButtonAuth = (arrRoutes: Array<RouteConfigs>) => {
if (!arrRoutes || !arrRoutes.length) return;
arrRoutes.forEach((v: RouteConfigs) => {
if (v.meta && v.meta.authority) {
this.buttonAuth.push(...v.meta.authority);
}
if (v.children) {
getButtonAuth(v.children);
}
});
};
getButtonAuth(this.wholeMenus);
},
async changeSetting(routes) {
await this.asyncActionRoutes(routes);
},
cacheOperate({ mode, name }: cacheType) {
switch (mode) {
@@ -61,11 +34,9 @@ export const usePermissionStore = defineStore({
break;
}
},
// 清空缓存页面
/** 清空缓存页面 */
clearAllCachePage() {
this.wholeMenus = [];
this.menusTree = [];
this.buttonAuth = [];
this.cachePageList = [];
}
}

View File

@@ -37,8 +37,8 @@ export type setType = {
};
export type userType = {
token: string;
name?: string;
username?: string;
roles?: Array<string>;
verifyCode?: string;
currentPage?: number;
};

View File

@@ -1,45 +1,56 @@
import { defineStore } from "pinia";
import { store } from "/@/store";
import { userType } from "./types";
import { router } from "/@/router";
import { routerArrays } from "/@/layout/types";
import { router, resetRouter } from "/@/router";
import { storageSession } from "@pureadmin/utils";
import { getLogin, refreshToken } from "/@/api/user";
import { getToken, setToken, removeToken } from "/@/utils/auth";
import { getLogin, refreshTokenApi } from "/@/api/user";
import { UserResult, RefreshTokenResult } from "/@/api/user";
import { useMultiTagsStoreHook } from "/@/store/modules/multiTags";
const data = getToken();
let token = "";
let name = "";
if (data) {
const dataJson = JSON.parse(data);
if (dataJson) {
token = dataJson?.accessToken;
name = dataJson?.name ?? "admin";
}
}
import {
type DataInfo,
setToken,
removeToken,
sessionKey
} from "/@/utils/auth";
export const useUserStore = defineStore({
id: "pure-user",
state: (): userType => ({
token,
name
username:
storageSession.getItem<DataInfo<number>>(sessionKey)?.username ?? "",
// 页面级别权限
roles: storageSession.getItem<DataInfo<number>>(sessionKey)?.roles ?? [],
// 前端生成的验证码(按实际需求替换)
verifyCode: "",
// 判断登录页面显示哪个组件0登录默认、1手机登录、2二维码登录、3注册、4忘记密码
currentPage: 0
}),
actions: {
SET_TOKEN(token) {
this.token = token;
/** 存储用户名 */
SET_USERNAME(username: string) {
this.username = username;
},
SET_NAME(name) {
this.name = name;
/** 存储角色 */
SET_ROLES(roles: Array<string>) {
this.roles = roles;
},
// 登入
/** 存储前端生成的验证码 */
SET_VERIFYCODE(verifyCode: string) {
this.verifyCode = verifyCode;
},
/** 存储登录页面显示哪个组件 */
SET_CURRENTPAGE(value: number) {
this.currentPage = value;
},
/** 登入 */
async loginByUsername(data) {
return new Promise<void>((resolve, reject) => {
return new Promise<UserResult>((resolve, reject) => {
getLogin(data)
.then(data => {
if (data) {
setToken(data);
resolve();
setToken(data.data);
resolve(data);
}
})
.catch(error => {
@@ -47,23 +58,28 @@ export const useUserStore = defineStore({
});
});
},
// 登出 清空缓存
/** 前端登出(不调用接口) */
logOut() {
this.token = "";
this.name = "";
this.username = "";
this.roles = [];
removeToken();
storageSession.clear();
useMultiTagsStoreHook().handleTags("equal", routerArrays);
router.push("/login");
useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
resetRouter();
},
// 刷新token
async refreshToken(data) {
removeToken();
return refreshToken(data).then(data => {
/** 刷新`token` */
async handRefreshToken(data) {
return new Promise<RefreshTokenResult>((resolve, reject) => {
refreshTokenApi(data)
.then(data => {
if (data) {
setToken(data);
return data;
setToken(data.data);
resolve(data);
}
})
.catch(error => {
reject(error);
});
});
}
}

View File

@@ -36,17 +36,12 @@ html.dark {
.arrow-left,
.arrow-right {
box-shadow: none;
border-right: 1px solid $border-style;
}
.arrow-right {
border-left: 1px solid $border-style;
}
.arrow-left,
.arrow-right,
.right-button li {
border-right: 1px solid $border-style;
}
}
/* vxe-table */

View File

@@ -33,10 +33,10 @@
}
.is-dark {
z-index: 99999 !important;
z-index: 9999 !important;
}
/* 重置buttoniconmargin */
/* 重置 el-buttoniconmargin */
.reset-margin [class*="el-icon"] + span {
margin-left: 2px !important;
}
@@ -46,7 +46,7 @@
padding: 0 !important;
}
/* nprogress适配ep的primary */
/* nprogress 适配 element-plus 的主题色 */
#nprogress {
& .bar {
background-color: var(--el-color-primary) !important;

View File

@@ -5,36 +5,11 @@
@import "./dark.scss";
@import "./tailwind.css";
/* 自定义全局 CssVar */
:root {
--pure-transition-duration: 0.016s;
}
body {
width: 100%;
height: 100%;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
text-rendering: optimizelegibility;
font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
"Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}
html {
width: 100%;
height: 100%;
box-sizing: border-box;
}
#app {
width: 100%;
height: 100%;
}
/* 头部用户信息样式重置 */
.hidden {
display: none !important;
}
/* 灰色模式 */
.html-grey {
filter: grayscale(100%);
@@ -45,14 +20,6 @@ html {
filter: invert(80%);
}
.pc-spacing {
margin: 10px;
}
.mobile-spacing {
margin: 0;
}
/* 重置 vxe-table 中 pager 样式 */
.vxe-pager .vxe-pager--num-btn:not(.is--disabled).is--active {
color: #fff !important;

View File

@@ -1,67 +1,49 @@
/*
1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4)
2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116)
*/
*,
::before,
::after {
box-sizing: border-box; /* 1 */
border-width: 0; /* 2 */
border-style: solid; /* 2 */
border-color: currentColor; /* 2 */
box-sizing: border-box;
border-width: 0;
border-style: solid;
border-color: currentColor;
}
/*
1. Use a consistent sensible line-height in all browsers.
2. Prevent adjustments of font size after orientation changes in iOS.
3. Use a more readable tab size.
4. Use the user's configured `sans` font-family by default.
*/
#app {
width: 100%;
height: 100%;
}
html {
line-height: 1.5; /* 1 */
-webkit-text-size-adjust: 100%; /* 2 */
-moz-tab-size: 4; /* 3 */
tab-size: 4; /* 3 */
line-height: 1.5;
-webkit-text-size-adjust: 100%;
-moz-tab-size: 4;
tab-size: 4;
width: 100%;
height: 100%;
box-sizing: border-box;
}
body {
margin: 0;
line-height: inherit;
width: 100%;
height: 100%;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
text-rendering: optimizelegibility;
font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
"Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}
/*
1. Remove the margin in all browsers.
2. Inherit line-height from `html` so users can set them as a class directly on the `html` element.
*/
body {
margin: 0; /* 1 */
line-height: inherit; /* 2 */
}
/*
1. Add the correct height in Firefox.
2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655)
3. Ensure horizontal rules are visible by default.
*/
hr {
height: 0; /* 1 */
color: inherit; /* 2 */
border-top-width: 1px; /* 3 */
height: 0;
color: inherit;
border-top-width: 1px;
}
/*
Add the correct text decoration in Chrome, Edge, and Safari.
*/
abbr:where([title]) {
text-decoration: underline dotted;
}
/*
Remove the default font size and weight for headings.
*/
h1,
h2,
h3,
@@ -72,50 +54,29 @@ h6 {
font-weight: inherit;
}
/*
Reset links to optimize for opt-in styling instead of opt-out.
*/
a {
color: inherit;
text-decoration: inherit;
}
/*
Add the correct font weight in Edge and Safari.
*/
b,
strong {
font-weight: bolder;
}
/*
1. Use the user's configured `mono` font family by default.
2. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp,
pre {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
"Liberation Mono", "Courier New", monospace; /* 1 */
font-size: 1em; /* 2 */
"Liberation Mono", "Courier New", monospace;
font-size: 1em;
}
/*
Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/*
Prevent `sub` and `sup` elements from affecting the line height in all browsers.
*/
sub,
sup {
font-size: 75%;
@@ -132,132 +93,73 @@ sup {
top: -0.5em;
}
/*
1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297)
2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016)
3. Remove gaps between table borders by default.
*/
table {
text-indent: 0; /* 1 */
border-color: inherit; /* 2 */
border-collapse: collapse; /* 3 */
text-indent: 0;
border-color: inherit;
border-collapse: collapse;
}
/*
1. Change the font styles in all browsers.
2. Remove the margin in Firefox and Safari.
3. Remove default padding in all browsers.
*/
button,
input,
optgroup,
select,
textarea {
font-family: inherit; /* 1 */
font-size: 100%; /* 1 */
line-height: inherit; /* 1 */
color: inherit; /* 1 */
margin: 0; /* 2 */
padding: 0; /* 3 */
font-family: inherit;
font-size: 100%;
line-height: inherit;
color: inherit;
margin: 0;
padding: 0;
}
/*
Remove the inheritance of text transform in Edge and Firefox.
*/
button,
select {
text-transform: none;
}
/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Remove default button styles.
*/
button,
[type="button"],
[type="reset"],
[type="submit"] {
-webkit-appearance: button; /* 1 */
background-image: none; /* 2 */
-webkit-appearance: button;
background-image: none;
}
/*
Use the modern Firefox focus style for all focusable elements.
*/
:-moz-focusring {
outline: auto;
}
/*
Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737)
*/
:-moz-ui-invalid {
box-shadow: none;
}
/*
Add the correct vertical alignment in Chrome and Firefox.
*/
progress {
vertical-align: baseline;
}
/*
Correct the cursor style of increment and decrement buttons in Safari.
*/
::-webkit-inner-spin-button,
::-webkit-outer-spin-button {
height: auto;
}
/*
1. Correct the odd appearance in Chrome and Safari.
2. Correct the outline style in Safari.
*/
[type="search"] {
-webkit-appearance: textfield; /* 1 */
outline-offset: -2px; /* 2 */
-webkit-appearance: textfield;
outline-offset: -2px;
}
/*
Remove the inner padding in Chrome and Safari on macOS.
*/
::-webkit-search-decoration {
-webkit-appearance: none;
}
/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button; /* 1 */
font: inherit; /* 2 */
-webkit-appearance: button;
font: inherit;
}
/*
Add the correct display in Chrome and Safari.
*/
summary {
display: list-item;
}
/*
Removes the default spacing and border for appropriate elements.
*/
blockquote,
dl,
dd,
@@ -291,47 +193,25 @@ menu {
padding: 0;
}
/*
Prevent resizing textareas horizontally by default.
*/
textarea {
resize: vertical;
}
/*
1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300)
2. Set the default placeholder color to the user's configured gray 400 color.
*/
input::placeholder,
textarea::placeholder {
opacity: 1; /* 1 */
color: #9ca3af; /* 2 */
opacity: 1;
color: #9ca3af;
}
/*
Set the default cursor for buttons.
*/
button,
[role="button"] {
cursor: pointer;
}
/*
Make sure disabled buttons don't get the pointer cursor.
*/
:disabled {
cursor: default;
}
/*
1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14)
2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210)
This can trigger a poorly considered lint error in some tools but is included by design.
*/
img,
svg,
video,
@@ -340,24 +220,16 @@ audio,
iframe,
embed,
object {
display: block; /* 1 */
vertical-align: middle; /* 2 */
display: block;
vertical-align: middle;
}
/*
Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14)
*/
img,
video {
max-width: 100%;
height: auto;
}
/*
Ensure the default browser behavior of the `hidden` attribute.
*/
[hidden] {
display: none;
}

View File

@@ -1,6 +1,5 @@
@mixin merge-style(
/* vertical模式下主体内容距离网页文档左侧的距离 */ $sideBarWidth
) {
/* $sideBarWidth: vertical 模式下主体内容距离网页文档左侧的距离 */
@mixin merge-style($sideBarWidth) {
$menuActiveText: #7a80b4;
@media screen and (min-width: 150px) and (max-width: 420px) {
@@ -23,6 +22,15 @@
margin-right: 5px;
}
.set-icon {
height: 48px;
width: 40px;
display: flex;
cursor: pointer;
align-items: center;
justify-content: center;
}
.main-container {
height: 100vh;
min-height: 100%;
@@ -232,7 +240,7 @@
/* 登录名 */
.el-dropdown-link,
/* 设置 */
.el-icon-setting {
.set-icon {
&:hover {
background: $menuHover;
}
@@ -271,15 +279,6 @@
border-radius: 50%;
}
}
.el-icon-setting {
height: 48px;
width: 40px;
padding: 12px;
display: flex;
cursor: pointer;
align-items: center;
}
}
.el-menu {
@@ -595,7 +594,7 @@ body[layout="vertical"] {
/* 登录名 */
.el-dropdown-link,
/* 设置 */
.el-icon-setting {
.set-icon {
&:hover {
background: #f6f6f6;
}

View File

@@ -3,14 +3,6 @@
@tailwind utilities;
@layer components {
.bg-dark {
@apply bg-bg_color;
}
.wh-full {
@apply w-full h-full;
}
.flex-c {
@apply flex justify-center items-center;
}

View File

@@ -1,43 +1,72 @@
import Cookies from "js-cookie";
import { storageSession } from "@pureadmin/utils";
import { useUserStoreHook } from "/@/store/modules/user";
const TokenKey = "authorized-token";
type paramsMapType = {
name: string;
expires: number;
export interface DataInfo<T> {
/** token */
accessToken: string;
};
// 获取token
export function getToken() {
// 此处与TokenKey相同此写法解决初始化时Cookies中不存在TokenKey报错
return Cookies.get("authorized-token");
/** `accessToken`的过期时间(时间戳) */
expires: T;
/** 用于调用刷新accessToken的接口时所需的token */
refreshToken: string;
/** 用户名 */
username?: string;
/** 当前登陆用户的角色 */
roles?: Array<string>;
}
// 设置token以及过期时间cookies、sessionStorage各一份
// 后端需要将用户信息和token以及过期时间都返回给前端过期时间主要用于刷新token
export function setToken(data) {
const { accessToken, expires, name } = data;
// 提取关键信息进行存储
const paramsMap: paramsMapType = {
name,
expires: Date.now() + parseInt(expires),
accessToken
};
const dataString = JSON.stringify(paramsMap);
useUserStoreHook().SET_TOKEN(accessToken);
useUserStoreHook().SET_NAME(name);
export const sessionKey = "user-info";
export const TokenKey = "authorized-token";
/** 获取`token` */
export function getToken(): DataInfo<number> {
// 此处与`TokenKey`相同,此写法解决初始化时`Cookies`中不存在`TokenKey`报错
return Cookies.get(TokenKey)
? JSON.parse(Cookies.get(TokenKey))
: storageSession.getItem(sessionKey);
}
/**
* @description 设置`token`以及一些必要信息并采用无感刷新`token`方案
* 无感刷新:后端返回`accessToken`(访问接口使用的`token`)、`refreshToken`(用于调用刷新`accessToken`的接口时所需的`token``refreshToken`的过期时间比如30天应大于`accessToken`的过期时间比如2小时、`expires``accessToken`的过期时间)
* 将`accessToken`、`expires`这两条信息放在key值为authorized-token的cookie里过期自动销毁
* 将`username`、`roles`、`refreshToken`、`expires`这四条信息放在key值为`user-info`的sessionStorage里浏览器关闭自动销毁
*/
export function setToken(data: DataInfo<Date>) {
let expires = 0;
const { accessToken, refreshToken } = data;
expires = new Date(data.expires).getTime();
const cookieString = JSON.stringify({ accessToken, expires });
expires > 0
? Cookies.set(TokenKey, dataString, {
expires: expires / 86400000
? Cookies.set(TokenKey, cookieString, {
expires: (expires - Date.now()) / 86400000
})
: Cookies.set(TokenKey, dataString);
sessionStorage.setItem(TokenKey, dataString);
: Cookies.set(TokenKey, cookieString);
function setSessionKey(username: string, roles: Array<string>) {
useUserStoreHook().SET_USERNAME(username);
useUserStoreHook().SET_ROLES(roles);
storageSession.setItem(sessionKey, {
refreshToken,
expires,
username,
roles
});
}
// 删除token
if (data.username && data.roles) {
const { username, roles } = data;
setSessionKey(username, roles);
} else {
const { username, roles } =
storageSession.getItem<DataInfo<number>>(sessionKey);
setSessionKey(username, roles);
}
}
/** 删除`token`以及key值为`user-info`的session信息 */
export function removeToken() {
Cookies.remove(TokenKey);
sessionStorage.removeItem(TokenKey);
sessionStorage.removeItem(sessionKey);
}

View File

@@ -1,6 +1,5 @@
import Axios, { AxiosInstance, AxiosRequestConfig } from "axios";
import {
resultType,
PureHttpError,
RequestMethods,
PureHttpResponse,
@@ -21,7 +20,7 @@ const defaultConfig: AxiosRequestConfig = {
// process.env.NODE_ENV === "production"
// ? VITE_PROXY_DOMAIN_REAL
// : VITE_PROXY_DOMAIN,
// 当前使用mock模拟请求将baseURL制空如果你的环境用到了http请求请删除下面的baseURL启用上面的baseURL并将11行、16行代码注释取消
// 当前使用mock模拟请求将baseURL制空如果你的环境用到了http请求请删除下面的baseURL启用上面的baseURL并将第10行、15行代码注释取消
baseURL: "",
timeout: 10000,
headers: {
@@ -38,16 +37,16 @@ class PureHttp {
this.httpInterceptorsRequest();
this.httpInterceptorsResponse();
}
// 初始化配置对象
/** 初始化配置对象 */
private static initConfig: PureHttpRequestConfig = {};
// 保存当前Axios实例对象
/** 保存当前Axios实例对象 */
private static axiosInstance: AxiosInstance = Axios.create(defaultConfig);
// 请求拦截
/** 请求拦截 */
private httpInterceptorsRequest(): void {
PureHttp.axiosInstance.interceptors.request.use(
(config: PureHttpRequestConfig) => {
async (config: PureHttpRequestConfig) => {
const $config = config;
// 开启进度条动画
NProgress.start();
@@ -60,26 +59,33 @@ class PureHttp {
PureHttp.initConfig.beforeRequestCallback($config);
return $config;
}
const token = getToken();
if (token) {
const data = JSON.parse(token);
/** 请求白名单放置一些不需要token的接口通过设置请求白名单防止token过期后再请求造成的死循环问题 */
const whiteList = ["/refreshToken", "/login"];
return whiteList.some(v => config.url.indexOf(v) > -1)
? config
: new Promise(resolve => {
const data = getToken();
if (data) {
const now = new Date().getTime();
const expired = parseInt(data.expires) - now <= 0;
if (expired) {
// token过期刷新
useUserStoreHook()
.refreshToken(data)
.then((res: resultType) => {
config.headers["Authorization"] = "Bearer " + res.accessToken;
return $config;
.handRefreshToken({ refreshToken: data.refreshToken })
.then(res => {
config.headers["Authorization"] =
"Bearer " + res.data.accessToken;
resolve($config);
});
} else {
config.headers["Authorization"] = "Bearer " + data.accessToken;
return $config;
config.headers["Authorization"] =
"Bearer " + data.accessToken;
resolve($config);
}
} else {
return $config;
resolve($config);
}
});
},
error => {
return Promise.reject(error);
@@ -87,7 +93,7 @@ class PureHttp {
);
}
// 响应拦截
/** 响应拦截 */
private httpInterceptorsResponse(): void {
const instance = PureHttp.axiosInstance;
instance.interceptors.response.use(
@@ -117,7 +123,7 @@ class PureHttp {
);
}
// 通用请求工具函数
/** 通用请求工具函数 */
public request<T>(
method: RequestMethods,
url: string,
@@ -144,7 +150,7 @@ class PureHttp {
});
}
// 单独抽离的post工具函数
/** 单独抽离的post工具函数 */
public post<T, P>(
url: string,
params?: T,
@@ -153,7 +159,7 @@ class PureHttp {
return this.request<P>("post", url, params, config);
}
// 单独抽离的get工具函数
/** 单独抽离的get工具函数 */
public get<T, P>(
url: string,
params?: T,

View File

@@ -11,7 +11,7 @@ defineOptions({
<noAccess />
<div class="ml-12">
<p
class="font-medium text-4xl mb-4"
class="font-medium text-4xl mb-4 dark:text-white"
v-motion
:initial="{
opacity: 0,

View File

@@ -11,7 +11,7 @@ defineOptions({
<noExist />
<div class="ml-12">
<p
class="font-medium text-4xl mb-4"
class="font-medium text-4xl mb-4 dark:text-white"
v-motion
:initial="{
opacity: 0,

View File

@@ -11,7 +11,7 @@ defineOptions({
<noServer />
<div class="ml-12">
<p
class="font-medium text-4xl mb-4"
class="font-medium text-4xl mb-4 dark:text-white"
v-motion
:initial="{
opacity: 0,

View File

@@ -3,16 +3,16 @@ import { useI18n } from "vue-i18n";
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { loginRules } from "./utils/rule";
import { ref, reactive, toRaw } from "vue";
import { initRouter } from "/@/router/utils";
import { useNav } from "/@/layout/hooks/useNav";
import { message } from "@pureadmin/components";
import type { FormInstance } from "element-plus";
import { storageSession } from "@pureadmin/utils";
import { $t, transformI18n } from "/@/plugins/i18n";
import { useLayout } from "/@/layout/hooks/useLayout";
import { useUserStoreHook } from "/@/store/modules/user";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import { useTranslationLang } from "/@/layout/hooks/useTranslationLang";
import { useDataThemeChange } from "/@/layout/hooks/useDataThemeChange";
@@ -32,6 +32,7 @@ initStorage();
const { t } = useI18n();
const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title, getDropdownItemStyle, getDropdownItemClass } = useNav();
const { locale, translationCh, translationEn } = useTranslationLang();
@@ -45,17 +46,17 @@ const onLogin = async (formEl: FormInstance | undefined) => {
if (!formEl) return;
await formEl.validate((valid, fields) => {
if (valid) {
// 模拟请求,需根据实际开发进行修改
setTimeout(() => {
loading.value = false;
storageSession.setItem("info", {
username: "admin",
accessToken: "eyJhbGciOiJIUzUxMiJ9.test"
});
initRouter("admin").then(() => {});
useUserStoreHook()
.loginByUsername({ username: ruleForm.username })
.then(res => {
if (res.success) {
// 获取后端路由
initRouter().then(() => {
message.success("登录成功");
router.push("/");
}, 2000);
});
}
});
} else {
loading.value = false;
return fields;
@@ -63,11 +64,24 @@ const onLogin = async (formEl: FormInstance | undefined) => {
});
};
dataThemeChange();
/** 使用公共函数,避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
if (code === "Enter") {
onLogin(ruleFormRef.value);
}
}
onMounted(() => {
window.document.addEventListener("keypress", onkeypress);
});
onBeforeUnmount(() => {
window.document.removeEventListener("keypress", onkeypress);
});
</script>
<template>
<div class="wh-full select-none">
<div class="select-none">
<img :src="bg" class="wave" />
<div class="flex-c absolute right-5 top-3">
<!-- 主题 -->
@@ -127,7 +141,6 @@ dataThemeChange();
:model="ruleForm"
:rules="loginRules"
size="large"
@keyup.enter="onLogin(ruleFormRef)"
>
<Motion :delay="100">
<el-form-item

View File

@@ -1,36 +1,80 @@
<script setup lang="ts">
import { ref } from "vue";
import type { StorageConfigs } from "/#/index";
import { storageSession } from "@pureadmin/utils";
import { type CSSProperties, computed } from "vue";
import { hasAuth, getAuths } from "/@/router/utils";
defineOptions({
name: "PermissionButton"
});
const auth = ref(
storageSession.getItem<StorageConfigs>("info").username || "admin"
);
function changRole(value) {
storageSession.setItem("info", {
username: value,
accessToken: `eyJhbGciOiJIUzUxMiJ9.${value}`
let width = computed((): CSSProperties => {
return {
width: "85vw"
};
});
window.location.reload();
}
</script>
<template>
<el-card>
<el-space direction="vertical" size="large">
<el-tag :style="width" size="large" effect="dark">
当前拥有的code列表{{ getAuths() }}
</el-tag>
<el-card shadow="never" :style="width">
<template #header>
<div class="card-header">组件方式判断权限</div>
</template>
<Auth value="btn_add">
<el-button type="success"> 拥有code'btn_add' 权限可见 </el-button>
</Auth>
<Auth :value="['btn_edit']">
<el-button type="primary"> 拥有code['btn_edit'] 权限可见 </el-button>
</Auth>
<Auth :value="['btn_add', 'btn_edit', 'btn_delete']">
<el-button type="danger">
拥有code['btn_add', 'btn_edit', 'btn_delete'] 权限可见
</el-button>
</Auth>
</el-card>
<el-card shadow="never" :style="width">
<template #header>
<div class="card-header">函数方式判断权限</div>
</template>
<el-button type="success" v-if="hasAuth('btn_add')">
拥有code'btn_add' 权限可见
</el-button>
<el-button type="primary" v-if="hasAuth(['btn_edit'])">
拥有code['btn_edit'] 权限可见
</el-button>
<el-button
type="danger"
v-if="hasAuth(['btn_add', 'btn_edit', 'btn_delete'])"
>
拥有code['btn_add', 'btn_edit', 'btn_delete'] 权限可见
</el-button>
</el-card>
<el-card shadow="never" :style="width">
<template #header>
<div class="card-header">
<el-radio-group v-model="auth" @change="changRole">
<el-radio-button label="admin" />
<el-radio-button label="test" />
</el-radio-group>
指令方式判断权限该方式不能动态修改权限
</div>
</template>
<p v-auth="'v-admin'">只有admin可看</p>
<p v-auth="'v-test'">只有test可看</p>
<el-button type="success" v-auth="'btn_add'">
拥有code'btn_add' 权限可见
</el-button>
<el-button type="primary" v-auth="['btn_edit']">
拥有code['btn_edit'] 权限可见
</el-button>
<el-button type="danger" v-auth="['btn_add', 'btn_edit', 'btn_delete']">
拥有code['btn_add', 'btn_edit', 'btn_delete'] 权限可见
</el-button>
</el-card>
</el-space>
</template>
<style lang="scss" scoped>
:deep(.el-tag) {
justify-content: start;
}
</style>

View File

@@ -1,53 +1,69 @@
<script setup lang="ts">
import { ref, unref } from "vue";
import type { StorageConfigs } from "/#/index";
import { storageSession } from "@pureadmin/utils";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { initRouter } from "/@/router/utils";
import { type CSSProperties, ref, computed } from "vue";
import { useUserStoreHook } from "/@/store/modules/user";
import { usePermissionStoreHook } from "/@/store/modules/permission";
defineOptions({
name: "PermissionPage"
});
let purview = ref<string>(
storageSession.getItem<StorageConfigs>("info").username
);
let width = computed((): CSSProperties => {
return {
width: "85vw"
};
});
function changRole() {
if (unref(purview) === "admin") {
storageSession.setItem("info", {
username: "test",
accessToken: "eyJhbGciOiJIUzUxMiJ9.test"
});
window.location.reload();
} else {
storageSession.setItem("info", {
username: "admin",
accessToken: "eyJhbGciOiJIUzUxMiJ9.admin"
});
window.location.reload();
let username = ref(useUserStoreHook()?.username);
const options = [
{
value: "admin",
label: "管理员角色"
},
{
value: "common",
label: "普通角色"
}
];
function onChange() {
useUserStoreHook()
.loginByUsername({ username: username.value })
.then(res => {
if (res.success) {
usePermissionStoreHook().clearAllCachePage();
initRouter();
}
});
}
</script>
<template>
<el-card>
<el-space direction="vertical" size="large">
<el-tag :style="width" size="large" effect="dark">
模拟后台根据不同角色返回对应路由具体参考完整版pure-admin代码
</el-tag>
<el-card shadow="never" :style="width">
<template #header>
<div class="card-header">
<span>
当前角色
<span style="font-size: 26px">{{ purview }}</span>
<p style="color: #ffa500">
查看左侧菜单变化(系统管理)模拟后台根据不同角色返回对应路由
</p>
</span>
<span>当前角色{{ username }}</span>
</div>
</template>
<el-button
type="primary"
@click="changRole"
:icon="useRenderIcon('user', { color: '#fff' })"
>
切换角色
</el-button>
<el-select v-model="username" @change="onChange">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</el-card>
</el-space>
</template>
<style lang="scss" scoped>
:deep(.el-tag) {
justify-content: start;
}
</style>

View File

@@ -42,5 +42,5 @@
"mock/*.ts",
"vite.config.ts"
],
"exclude": ["node_modules", "dist", "**/*.js"]
"exclude": ["node_modules", "dist", "**/*.js", "index.html"]
}

1
types/global.d.ts vendored
View File

@@ -14,6 +14,7 @@ declare module "vue" {
IconifyIconOffline: typeof import("../src/components/ReIcon")["IconifyIconOffline"];
IconifyIconOnline: typeof import("../src/components/ReIcon")["IconifyIconOnline"];
FontIcon: typeof import("../src/components/ReIcon")["FontIcon"];
Auth: typeof import("../src/components/ReAuth")["Auth"];
}
}

View File

@@ -74,8 +74,10 @@ export interface RouteChildrenConfigsTable {
showLink?: boolean;
/** 是否显示父级菜单 `可选` */
showParent?: boolean;
/** 路由权限设置 `可选` */
authority?: Array<string>;
/** 页面级别权限设置 `可选` */
roles?: Array<string>;
/** 按钮级别权限设置 `可选` */
auths?: Array<string>;
/** 路由组件缓存(开启 `true`、关闭 `false``可选` */
keepAlive?: boolean;
/** 内嵌的`iframe`链接 `可选` */

View File

@@ -10,3 +10,6 @@ declare module "*.scss" {
}
declare module "vuedraggable/src/vuedraggable";
declare module "@pureadmin/components";
declare module "@pureadmin/theme";
declare module "@pureadmin/theme/dist/browser-utils";

View File

@@ -5,15 +5,15 @@ import { warpperEnv, regExps } from "./build";
import { getPluginsList } from "./build/plugins";
import { UserConfigExport, ConfigEnv, loadEnv } from "vite";
// 当前执行node命令时文件夹的地址工作目录
/** 当前执行node命令时文件夹的地址工作目录 */
const root: string = process.cwd();
// 路径查找
/** 路径查找 */
const pathResolve = (dir: string): string => {
return resolve(__dirname, ".", dir);
};
// 设置别名
/** 设置别名 */
const alias: Record<string, string> = {
"/@": pathResolve("src"),
"@build": pathResolve("build")