Compare commits

..

30 Commits

Author SHA1 Message Date
xiaoxian521
6ceb37624f release: update 3.6.1 2022-10-27 02:46:26 +08:00
xiaoxian521
fdf12660c1 feat: 打包构建添加可选 gzipbrotli 压缩模式 2022-10-27 02:19:23 +08:00
xiaoxian521
49cdcf216f feat: 添加打包是否启动cdn替换本地库配置,默认false不启动 2022-10-26 19:51:06 +08:00
xiaoxian521
936070c9ce chore: 同步完整版代码 2022-10-26 11:25:45 +08:00
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
xiaoxian521
cdaa4cdba8 release: update 3.5.0 2022-09-10 21:53:46 +08:00
xiaoxian521
496947b524 chore: update 2022-09-09 00:04:29 +08:00
xiaoxian521
d48058c28f feat: 添加cssnano,打包时压缩css体积 2022-09-08 17:15:22 +08:00
xiaoxian521
820f724d5b chore: use pnpm shell-emulator instead of cross-env 2022-09-07 21:53:26 +08:00
xiaoxian521
63e2ddc171 chore: 简化登录页 2022-09-07 16:47:57 +08:00
xiaoxian521
60cdaf4697 refactor: use tailwindcss replace unocss 2022-09-07 16:04:26 +08:00
xiaoxian521
d3cabb0f33 fix: token过期,刷新死循环 2022-09-07 15:23:06 +08:00
xiaoxian521
97193a71a6 chore: update 2022-09-05 22:22:36 +08:00
xiaoxian521
f8694e953c chore: update 2022-09-03 14:06:56 +08:00
xiaoxian521
55f97fce96 chore: update 2022-08-31 11:33:44 +08:00
xiaoxian521
29144aba44 perf: 重置路由时,清空缓存页面 2022-08-24 16:11:41 +08:00
xiaoxian521
9a448143ae chore: window.process定义在index.html中,防止低版本浏览器报错 2022-08-24 09:48:16 +08:00
xiaoxian521
a85a2f9022 chore: 开启vscode括号对指南 2022-08-23 20:49:25 +08:00
xiaoxian521
20fee1418c style: update 2022-08-23 18:02:00 +08:00
xiaoxian521
2888f8c4f1 release: update 3.4.6 2022-08-23 10:43:33 +08:00
xiaoxian521
c07e60e114 release: update 3.4.5 2022-08-22 21:34:55 +08:00
xiaoxian521
13427998f3 chore: lock responsive-storage version 1.0.11 2022-08-09 13:19:55 +08:00
xiaoxian521
46355bf5bb chore: update @pureadmin/theme 2022-07-04 13:26:07 +08:00
162 changed files with 5447 additions and 6336 deletions

View File

@@ -9,3 +9,11 @@ VITE_PROXY_DOMAIN_REAL = ""
# 是否为打包后的文件提供传统浏览器兼容性支持 支持 true 不支持 false # 是否为打包后的文件提供传统浏览器兼容性支持 支持 true 不支持 false
VITE_LEGACY = false VITE_LEGACY = false
# 是否在打包时使用cdn替换本地库 替换 true 不替换 false
VITE_CDN = false
# 是否启用gzip压缩或brotli压缩分两种情况删除原始文件和不删除原始文件
# 压缩时不删除原始文件的配置gzip、brotli、both同时开启 gzip 与 brotli 压缩、none不开启压缩默认
# 压缩时删除原始文件的配置gzip-clear、brotli-clear、both-clear同时开启 gzip 与 brotli 压缩、none不开启压缩默认
VITE_COMPRESSION = "none"

View File

@@ -12,3 +12,11 @@ VITE_PROXY_DOMAIN_REAL = ""
# 是否为打包后的文件提供传统浏览器兼容性支持 支持 true 不支持 false # 是否为打包后的文件提供传统浏览器兼容性支持 支持 true 不支持 false
VITE_LEGACY = false VITE_LEGACY = false
# 是否在打包时使用cdn替换本地库 替换 true 不替换 false
VITE_CDN = false
# 是否启用gzip压缩或brotli压缩分两种情况删除原始文件和不删除原始文件
# 压缩时不删除原始文件的配置gzip、brotli、both同时开启 gzip 与 brotli 压缩、none不开启压缩默认
# 压缩时删除原始文件的配置gzip-clear、brotli-clear、both-clear同时开启 gzip 与 brotli 压缩、none不开启压缩默认
VITE_COMPRESSION = "none"

View File

@@ -2,3 +2,9 @@ public
dist dist
*.d.ts *.d.ts
package.json package.json
.eslintrc.js
.prettierrc.js
commitlint.config.js
postcss.config.js
tailwind.config.js
stylelint.config.js

View File

@@ -49,6 +49,29 @@ module.exports = {
jsx: true jsx: true
} }
}, },
overrides: [
{
files: ["*.ts", "*.vue"],
rules: {
"no-undef": "off"
}
},
{
files: ["*.vue"],
parser: "vue-eslint-parser",
parserOptions: {
parser: "@typescript-eslint/parser",
extraFileExtensions: [".vue"],
ecmaVersion: "latest",
ecmaFeatures: {
jsx: true
}
},
rules: {
"no-undef": "off"
}
}
],
rules: { rules: {
"vue/no-v-html": "off", "vue/no-v-html": "off",
"vue/require-default-prop": "off", "vue/require-default-prop": "off",

3
.gitignore vendored
View File

@@ -4,7 +4,7 @@ dist
dist-ssr dist-ssr
*.local *.local
.eslintcache .eslintcache
.stylelintcache report.html
yarn.lock yarn.lock
npm-debug.log* npm-debug.log*
@@ -18,3 +18,4 @@ tests/**/coverage/
*.ntvs* *.ntvs*
*.njsproj *.njsproj
*.sln *.sln
tsconfig.tsbuildinfo

View File

@@ -1,6 +1,6 @@
module.exports = { module.exports = {
"*.{js,jsx,ts,tsx}": ["eslint --fix", "prettier --write"], "*.{js,jsx,ts,tsx}": ["eslint --fix", "prettier --write"],
"{!(package)*.json,.!(browserslist)*rc}": ["prettier --write--parser json"], "{!(package)*.json}": ["prettier --write--parser json"],
"package.json": ["prettier --write"], "package.json": ["prettier --write"],
"*.vue": ["eslint --fix", "prettier --write", "stylelint --fix"], "*.vue": ["eslint --fix", "prettier --write", "stylelint --fix"],
"*.{vue,css,scss,postcss,less}": ["stylelint --fix", "prettier --write"], "*.{vue,css,scss,postcss,less}": ["stylelint --fix", "prettier --write"],

3
.npmrc Normal file
View File

@@ -0,0 +1,3 @@
shamefully-hoist=true
strict-peer-dependencies=false
shell-emulator=true

View File

@@ -1,15 +1,18 @@
{ {
"recommendations": [ "recommendations": [
"christian-kohler.path-intellisense",
"vscode-icons-team.vscode-icons", "vscode-icons-team.vscode-icons",
"davidanson.vscode-markdownlint", "davidanson.vscode-markdownlint",
"stylelint.vscode-stylelint", "stylelint.vscode-stylelint",
"bradlc.vscode-tailwindcss",
"dbaeumer.vscode-eslint", "dbaeumer.vscode-eslint",
"esbenp.prettier-vscode", "esbenp.prettier-vscode",
"johnsoncodehk.volar",
"lokalise.i18n-ally", "lokalise.i18n-ally",
"redhat.vscode-yaml",
"csstools.postcss",
"mikestead.dotenv", "mikestead.dotenv",
"eamodio.gitlens", "eamodio.gitlens",
"antfu.iconify", "antfu.iconify",
"antfu.unocss" "Vue.volar"
] ]
} }

View File

@@ -6,6 +6,7 @@
}, },
"editor.tabSize": 2, "editor.tabSize": 2,
"editor.formatOnPaste": true, "editor.formatOnPaste": true,
"editor.guides.bracketPairs": "active",
"files.autoSave": "afterDelay", "files.autoSave": "afterDelay",
"git.confirmSync": false, "git.confirmSync": false,
"workbench.startupEditor": "newUntitledFile", "workbench.startupEditor": "newUntitledFile",
@@ -33,5 +34,6 @@
"i18n-ally.enabledParsers": ["yaml", "js"], "i18n-ally.enabledParsers": ["yaml", "js"],
"i18n-ally.sourceLanguage": "en", "i18n-ally.sourceLanguage": "en",
"i18n-ally.displayLanguage": "zh-CN", "i18n-ally.displayLanguage": "zh-CN",
"i18n-ally.enabledFrameworks": ["vue"] "i18n-ally.enabledFrameworks": ["vue"],
"iconify.excludes": ["el"]
} }

View File

@@ -6,7 +6,7 @@
## introduce ## introduce
The lite version is based on the shelf extracted from [vue-pure-admin](https://github.com/xiaoxian521/vue-pure-admin), which contains the main functions and is more suitable for actual project development, the packaged size is only more than `3MB` The lite version is based on the shelf extracted from [vue-pure-admin](https://github.com/xiaoxian521/vue-pure-admin), which contains the main functions and is more suitable for actual project development, the packaged size is only `3MB`, and will permanently sync the full version of the code
## Supporting Video ## Supporting Video
@@ -15,7 +15,9 @@ The lite version is based on the shelf extracted from [vue-pure-admin](https://g
## Docs ## Docs
- [Click Watch Docs](https://pure-admin-doc.vercel.app) - [Click me to view the domestic documentation site](http://yiming_chang.gitee.io/pure-admin-doc)
- [Click me to view foreign document site 1](https://xiaoxian521.github.io/pure-admin-doc)
- [Click me to view foreign document site 2](https://pure-admin-doc.vercel.app)
## Usage ## Usage

View File

@@ -6,7 +6,7 @@
## 介绍 ## 介绍
精简版是基于[vue-pure-admin](https://github.com/xiaoxian521/vue-pure-admin)提炼出的架子,包含主体功能,更适合实际项目开发,打包后的大小仅 `3MB` 精简版是基于 [vue-pure-admin](https://github.com/xiaoxian521/vue-pure-admin) 提炼出的架子,包含主体功能,更适合实际项目开发,打包后的大小仅 `3MB`,并且会永久同步完整版的代码
## 配套视频 ## 配套视频
@@ -15,7 +15,9 @@
## 配套文档 ## 配套文档
- [点我查看文档](https://pure-admin-doc.vercel.app) - [点我查看国内文档](http://yiming_chang.gitee.io/pure-admin-doc)
- [点我查看国外文档站 1](https://xiaoxian521.github.io/pure-admin-doc)
- [点我查看国外文档站 2](https://pure-admin-doc.vercel.app)
## 维护者 ## 维护者
@@ -29,9 +31,9 @@
## QQ 交流群 ## QQ 交流群
群里严禁`黄``赌``毒``vpn`等违法行为! 一群已满,下面是二群,群里严禁 `黄``赌``毒``vpn` 等违法行为!
<img src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/f0697596aec84661b724f6eebdf8db17~tplv-k3u1fbpfcp-watermark.awebp?" width="150px" height="225px" /> <img src="http://yiming_chang.gitee.io/pure-admin-doc/img/support/qq.png" width="150px" height="225px" />
## 用法 ## 用法
@@ -47,12 +49,12 @@ pnpm add 包名
pnpm remove 包名 pnpm remove 包名
我认为你应该先 fork 项目去开发,以便我更新时您可以同步拉取更新!!! 我认为你应该先 `fork` 项目去开发,以便我更新时您可以同步拉取更新!!!
## ⚠️ 注意 ## ⚠️ 注意
- 精简版不接受任何 issues 和 pr,如果有问题请到完整版 https://github.com/xiaoxian521/vue-pure-admin/issues/new/choose 去提,谢谢!!! - 精简版不接受任何 `issues``pr`,如果有问题请到完整版 [issues](https://github.com/xiaoxian521/vue-pure-admin/issues/new/choose) 去提,谢谢!!!
- 不要使用`delete-i18n`分支代码,这个分支只是给你们完全删除国际化的参考,不会同步代码的!!![完全删除国际化教程](https://www.bilibili.com/video/BV1Ru411B7k3/),请务必使用`main`分支的代码!!! - 不要使用 `delete-i18n` 分支代码,这个分支只是给你们完全删除国际化的参考,不会同步代码的!!! [完全删除国际化教程](https://www.bilibili.com/video/BV1Ru411B7k3/) ,请务必使用 `main` 分支的代码!!!
## 许可证 ## 许可证

67
build/cdn.ts Normal file
View File

@@ -0,0 +1,67 @@
import { Plugin as importToCDN } from "vite-plugin-cdn-import";
/**
* @description 打包时采用`cdn`模式仅限外网使用默认不采用如果需要采用cdn模式请在 .env.production 文件,将 VITE_CDN 设置成true
* 平台采用国内cdnhttps://www.bootcdn.cn当然你也可以选择 https://unpkg.com 或者 https://www.jsdelivr.com
* 提醒mockjs不能用cdn模式引入会报错。正确的方式是生产环境删除mockjs使用真实的后端请求
* 注意上面提到的仅限外网使用也不是完全肯定的如果你们公司内网部署的有相关js、css文件也可以将下面配置对应改一下整一套内网版cdn
*/
export const cdn = importToCDN({
//prodUrl解释 name: 对应下面modules的nameversion: 自动读取本地package.json中dependencies依赖中对应包的版本号path: 对应下面modules的path
prodUrl: "https://cdn.bootcdn.net/ajax/libs/{name}/{version}/{path}",
modules: [
{
name: "vue",
var: "Vue",
path: "vue.global.prod.min.js"
},
{
name: "vue-router",
var: "VueRouter",
path: "vue-router.global.min.js"
},
{
name: "vue-i18n",
var: "VueI18n",
path: "vue-i18n.runtime.global.prod.min.js"
},
// 项目中没有直接安装vue-demi但是pinia用到了所以需要在引入pinia前引入vue-demihttps://github.com/vuejs/pinia/blob/v2/packages/pinia/package.json#L77
{
name: "vue-demi",
var: "VueDemi",
path: "index.iife.min.js"
},
{
name: "pinia",
var: "Pinia",
path: "pinia.iife.min.js"
},
{
name: "element-plus",
var: "ElementPlus",
path: "index.full.min.js",
css: "index.min.css"
},
{
name: "axios",
var: "axios",
path: "axios.min.js"
},
{
name: "dayjs",
var: "dayjs",
path: "dayjs.min.js"
},
{
name: "echarts",
var: "echarts",
path: "echarts.min.js"
},
{
name: "lodash",
var: "lodash",
// 可写`完整路径`,会替换`prodUrl`
path: "https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.min.js"
}
]
});

63
build/compress.ts Normal file
View File

@@ -0,0 +1,63 @@
import type { Plugin } from "vite";
import { isArray } from "@pureadmin/utils";
import compressPlugin from "vite-plugin-compression";
export const configCompressPlugin = (
compress: ViteCompression
): Plugin | Plugin[] => {
if (compress === "none") return null;
const gz = {
// 生成的压缩包后缀
ext: ".gz",
// 体积大于threshold才会被压缩
threshold: 0,
// 默认压缩.js|mjs|json|css|html后缀文件设置成true压缩全部文件
filter: () => true,
// 压缩后是否删除原始文件
deleteOriginFile: false
};
const br = {
ext: ".br",
algorithm: "brotliCompress",
threshold: 0,
filter: () => true,
deleteOriginFile: false
};
const codeList = [
{ k: "gzip", v: gz },
{ k: "brotli", v: br },
{ k: "both", v: [gz, br] }
];
const plugins: Plugin[] = [];
codeList.forEach(item => {
if (compress.includes(item.k)) {
if (compress.includes("clear")) {
if (isArray(item.v)) {
item.v.forEach(vItem => {
plugins.push(
compressPlugin(Object.assign(vItem, { deleteOriginFile: true }))
);
});
} else {
plugins.push(
compressPlugin(Object.assign(item.v, { deleteOriginFile: true }))
);
}
} else {
if (isArray(item.v)) {
item.v.forEach(vItem => {
plugins.push(compressPlugin(vItem));
});
} else {
plugins.push(compressPlugin(item.v));
}
}
}
});
return plugins;
};

View File

@@ -1,13 +1,15 @@
// 处理环境变量 /** 处理环境变量 */
const warpperEnv = (envConf: Recordable): ViteEnv => { const warpperEnv = (envConf: Recordable): ViteEnv => {
// 此处为默认值,无需修改 /** 此处为默认值,无需修改 */
const ret: ViteEnv = { const ret: ViteEnv = {
VITE_PORT: 8848, VITE_PORT: 8848,
VITE_PUBLIC_PATH: "", VITE_PUBLIC_PATH: "",
VITE_PROXY_DOMAIN: "", VITE_PROXY_DOMAIN: "",
VITE_PROXY_DOMAIN_REAL: "", VITE_PROXY_DOMAIN_REAL: "",
VITE_ROUTER_HISTORY: "", VITE_ROUTER_HISTORY: "",
VITE_LEGACY: false VITE_LEGACY: false,
VITE_CDN: false,
VITE_COMPRESSION: "none"
}; };
for (const envName of Object.keys(envConf)) { for (const envName of Object.keys(envConf)) {
@@ -28,12 +30,12 @@ const warpperEnv = (envConf: Recordable): ViteEnv => {
return ret; return ret;
}; };
// 跨域代理重写 /** 跨域代理重写 */
const regExps = (value: string, reg: string): string => { const regExps = (value: string, reg: string): string => {
return value.replace(new RegExp(reg, "g"), ""); return value.replace(new RegExp(`^${reg}`, "g"), "");
}; };
// 环境变量 /** 环境变量 */
const loadEnv = (): ViteEnv => { const loadEnv = (): ViteEnv => {
return import.meta.env; return import.meta.env;
}; };

View File

@@ -1,45 +1,10 @@
import { readdir, stat } from "fs";
import type { Plugin } from "vite"; import type { Plugin } from "vite";
import dayjs, { Dayjs } from "dayjs"; import dayjs, { Dayjs } from "dayjs";
import { sum } from "lodash-unified";
import duration from "dayjs/plugin/duration"; import duration from "dayjs/plugin/duration";
import { green, blue, bold } from "picocolors"; import { green, blue, bold } from "picocolors";
import { getPackageSize } from "@pureadmin/utils";
dayjs.extend(duration); dayjs.extend(duration);
const staticPath = "dist";
const fileListTotal: number[] = [];
const recursiveDirectory = (folder: string, callback: Function): void => {
readdir(folder, (err, files: string[]) => {
if (err) throw err;
let count = 0;
const checkEnd = () => {
++count == files.length && callback();
};
files.forEach((item: string) => {
stat(folder + "/" + item, async (err, stats) => {
if (err) throw err;
if (stats.isFile()) {
fileListTotal.push(stats.size);
checkEnd();
} else if (stats.isDirectory()) {
recursiveDirectory(`${staticPath}/${item}/`, checkEnd);
}
});
});
files.length === 0 && callback();
});
};
const formatBytes = (a: number, b?: number): string => {
if (0 == a) return "0 Bytes";
const c = 1024,
d = b || 2,
e = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
f = Math.floor(Math.log(a) / Math.log(c));
return parseFloat((a / Math.pow(c, f)).toFixed(d)) + " " + e[f];
};
export function viteBuildInfo(): Plugin { export function viteBuildInfo(): Plugin {
let config: { command: string }; let config: { command: string };
let startTime: Dayjs; let startTime: Dayjs;
@@ -50,34 +15,34 @@ export function viteBuildInfo(): Plugin {
config = resolvedConfig; config = resolvedConfig;
}, },
buildStart() { buildStart() {
console.log(
bold(
green(
`👏欢迎使用${blue(
"[vue-pure-admin]"
)}如果您感觉不错记得点击后面链接给个star哦💖 https://github.com/xiaoxian521/vue-pure-admin`
)
)
);
if (config.command === "build") { if (config.command === "build") {
startTime = dayjs(new Date()); startTime = dayjs(new Date());
} }
}, },
closeBundle() { closeBundle() {
if (config.command === "build") { if (config.command === "build") {
console.log(
bold(
green(
`👏欢迎使用${blue(
"[vue-pure-admin]"
)}如果您感觉不错记得点击后面链接给个star哦💖 https://github.com/xiaoxian521/vue-pure-admin`
)
)
);
endTime = dayjs(new Date()); endTime = dayjs(new Date());
recursiveDirectory(staticPath, () => { getPackageSize({
console.log( callback: (size: string) => {
bold( console.log(
green( bold(
`恭喜打包完成🎉(总用时${dayjs green(
.duration(endTime.diff(startTime)) `🎉恭喜打包完成(总用时${dayjs
.format("mm分ss秒")},打包后的大小为${formatBytes( .duration(endTime.diff(startTime))
sum(fileListTotal) .format("mm分ss秒")},打包后的大小为${size}`
)}` )
) )
) );
); }
}); });
} }
} }

View File

@@ -1,19 +1,26 @@
import { cdn } from "./cdn";
import { resolve } from "path"; import { resolve } from "path";
import Unocss from "unocss/vite";
import vue from "@vitejs/plugin-vue"; import vue from "@vitejs/plugin-vue";
import { viteBuildInfo } from "./info"; import { viteBuildInfo } from "./info";
import svgLoader from "vite-svg-loader"; import svgLoader from "vite-svg-loader";
import legacy from "@vitejs/plugin-legacy"; import legacy from "@vitejs/plugin-legacy";
import vueJsx from "@vitejs/plugin-vue-jsx"; import vueJsx from "@vitejs/plugin-vue-jsx";
import { viteMockServe } from "vite-plugin-mock"; import { viteMockServe } from "vite-plugin-mock";
import { configCompressPlugin } from "./compress";
import VueI18n from "@intlify/vite-plugin-vue-i18n"; import VueI18n from "@intlify/vite-plugin-vue-i18n";
// import ElementPlus from "unplugin-element-plus/vite"; // import ElementPlus from "unplugin-element-plus/vite";
import { visualizer } from "rollup-plugin-visualizer"; import { visualizer } from "rollup-plugin-visualizer";
import removeConsole from "vite-plugin-remove-console"; import removeConsole from "vite-plugin-remove-console";
import themePreprocessorPlugin from "@pureadmin/theme"; import themePreprocessorPlugin from "@pureadmin/theme";
import { genScssMultipleScopeVars } from "/@/layout/theme"; import { genScssMultipleScopeVars } from "/@/layout/theme";
import DefineOptions from "unplugin-vue-define-options/vite";
export function getPluginsList(command, VITE_LEGACY) { export function getPluginsList(
command: string,
VITE_LEGACY: boolean,
VITE_CDN: boolean,
VITE_COMPRESSION: ViteCompression
) {
const prodMock = true; const prodMock = true;
const lifecycle = process.env.npm_lifecycle_event; const lifecycle = process.env.npm_lifecycle_event;
return [ return [
@@ -26,9 +33,11 @@ export function getPluginsList(command, VITE_LEGACY) {
}), }),
// jsx、tsx语法支持 // jsx、tsx语法支持
vueJsx(), vueJsx(),
Unocss(), VITE_CDN ? cdn : null,
configCompressPlugin(VITE_COMPRESSION),
DefineOptions(),
// 线上环境删除console // 线上环境删除console
removeConsole(), removeConsole({ external: ["src/assets/iconfont/iconfont.js"] }),
viteBuildInfo(), viteBuildInfo(),
// 自定义主题 // 自定义主题
themePreprocessorPlugin({ themePreprocessorPlugin({

View File

@@ -2,9 +2,14 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="renderer" content="webkit" />
<meta
name="viewport"
content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=0"
/>
<title>pure-admin-thin</title> <title>pure-admin-thin</title>
<link rel="icon" href="/favicon.ico" />
<script> <script>
window.process = {}; window.process = {};
</script> </script>
@@ -31,9 +36,7 @@
border-radius: 50%; border-radius: 50%;
width: 2.5em; width: 2.5em;
height: 2.5em; height: 2.5em;
-webkit-animation-fill-mode: both;
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; animation: loadAnimation 1.8s infinite ease-in-out;
} }
@@ -43,10 +46,7 @@
margin: 80px auto; margin: 80px auto;
position: relative; position: relative;
text-indent: -9999em; text-indent: -9999em;
-webkit-transform: translateZ(0);
-ms-transform: translateZ(0);
transform: translateZ(0); transform: translateZ(0);
-webkit-animation-delay: -0.16s;
animation-delay: -0.16s; animation-delay: -0.16s;
top: 0; top: 0;
transform: translate(-50%, 0); transform: translate(-50%, 0);
@@ -61,7 +61,6 @@
.loader:before { .loader:before {
left: -3.5em; left: -3.5em;
-webkit-animation-delay: -0.32s;
animation-delay: -0.32s; animation-delay: -0.32s;
} }
@@ -69,18 +68,6 @@
left: 3.5em; 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 { @keyframes loadAnimation {
0%, 0%,
80%, 80%,

View File

@@ -18,10 +18,14 @@ buttons:
hscloseRightTabs: Close RightTabs hscloseRightTabs: Close RightTabs
hscloseOtherTabs: Close OtherTabs hscloseOtherTabs: Close OtherTabs
hscloseAllTabs: Close AllTabs hscloseAllTabs: Close AllTabs
hswholeFullScreen: Whole FullScreen
hswholeExitFullScreen: Whole ExitFullScreen
hscontentFullScreen: Content FullScreen
hscontentExitFullScreen: Content ExitFullScreen
menus: menus:
hshome: Home hshome: Home
hslogin: Login hslogin: Login
hserror: Error Page hsabnormal: Abnormal Page
hsfourZeroFour: "404" hsfourZeroFour: "404"
hsfourZeroOne: "403" hsfourZeroOne: "403"
hsFive: "500" hsFive: "500"
@@ -30,3 +34,10 @@ menus:
permissionButton: Button Permission permissionButton: Button Permission
status: status:
hsLoad: Loading... hsLoad: Loading...
login:
username: Username
password: Password
login: Login
usernameReg: Please enter username
passwordReg: Please enter password
passwordRuleReg: The password format should be any combination of 8-18 digits

View File

@@ -3,7 +3,7 @@ buttons:
hsfullscreen: 全屏 hsfullscreen: 全屏
hsexitfullscreen: 退出全屏 hsexitfullscreen: 退出全屏
hsrefreshRoute: 刷新路由 hsrefreshRoute: 刷新路由
hslogin: hslogin:
hsadd: 新增 hsadd: 新增
hsmark: 标记/取消 hsmark: 标记/取消
hssave: 保存 hssave: 保存
@@ -18,10 +18,14 @@ buttons:
hscloseRightTabs: 关闭右侧标签页 hscloseRightTabs: 关闭右侧标签页
hscloseOtherTabs: 关闭其他标签页 hscloseOtherTabs: 关闭其他标签页
hscloseAllTabs: 关闭全部标签页 hscloseAllTabs: 关闭全部标签页
hswholeFullScreen: 整体页面全屏
hswholeExitFullScreen: 整体页面退出全屏
hscontentFullScreen: 内容区全屏
hscontentExitFullScreen: 内容区退出全屏
menus: menus:
hshome: 首页 hshome: 首页
hslogin: hslogin:
hserror: 错误页面 hsabnormal: 异常页面
hsfourZeroFour: "404" hsfourZeroFour: "404"
hsfourZeroOne: "403" hsfourZeroOne: "403"
hsFive: "500" hsFive: "500"
@@ -30,3 +34,10 @@ menus:
permissionButton: 按钮权限 permissionButton: 按钮权限
status: status:
hsLoad: 加载中... hsLoad: 加载中...
login:
username: 账号
password: 密码
login: 登录
usernameReg: 请输入账号
passwordReg: 请输入密码
passwordRuleReg: 密码格式应为8-18位数字、字母、符号的任意两种组合

View File

@@ -1,55 +1,49 @@
// 根据角色动态生成路由 // 模拟后端动态生成路由
import { MockMethod } from "vite-plugin-mock"; import { MockMethod } from "vite-plugin-mock";
/**
* roles页面级别权限这里模拟二种 "admin"、"common"
* admin管理员角色
* common普通角色
*/
const permissionRouter = { const permissionRouter = {
path: "/permission", path: "/permission",
redirect: "/permission/page/index",
meta: { meta: {
title: "menus.permission", title: "menus.permission",
icon: "lollipop", icon: "lollipop",
rank: 7 rank: 10
}, },
children: [ children: [
{ {
path: "/permission/page/index", path: "/permission/page/index",
name: "permissionPage", name: "PermissionPage",
meta: { meta: {
roles: ["admin", "common"],
title: "menus.permissionPage" title: "menus.permissionPage"
} }
}, },
{ {
path: "/permission/button/index", path: "/permission/button/index",
name: "permissionButton", name: "PermissionButton",
meta: { meta: {
title: "menus.permissionButton", 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 [ export default [
{ {
url: "/getAsyncRoutes", url: "/getAsyncRoutes",
method: "get", method: "get",
response: ({ query }) => { response: () => {
if (query.name === "admin") { return {
return { success: true,
code: 0, data: [permissionRouter]
info: [setDifAuthority("v-admin", permissionRouter)] };
};
} else {
return {
code: 0,
info: [setDifAuthority("v-test", permissionRouter)]
};
}
} }
} }
] as MockMethod[]; ] 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,18 +1,20 @@
{ {
"name": "pure-admin-thin", "name": "pure-admin-thin",
"version": "3.3.0", "version": "3.6.1",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "cross-env --max_old_space_size=4096 vite", "dev": "NODE_OPTIONS=--max-old-space-size=4096 vite",
"serve": "pnpm dev", "serve": "pnpm dev",
"build": "rimraf dist && cross-env vite build", "build": "rimraf dist && NODE_OPTIONS=--max-old-space-size=8192 vite build",
"build:staging": "rimraf dist && cross-env vite build --mode staging", "build:staging": "rimraf dist && vite build --mode staging",
"report": "rimraf dist && cross-env vite build", "report": "rimraf dist && vite build",
"preview": "vite preview", "preview": "vite preview",
"preview:build": "pnpm build && vite preview", "preview:build": "pnpm build && vite preview",
"typecheck": "tsc --noEmit && vue-tsc --noEmit --skipLibCheck",
"cloc": "NODE_OPTIONS=--max-old-space-size=4096 cloc . --exclude-dir=node_modules --exclude-lang=YAML",
"clean:cache": "rm -rf node_modules && rm -rf .eslintcache && pnpm install", "clean:cache": "rm -rf node_modules && rm -rf .eslintcache && pnpm install",
"lint:eslint": "eslint --cache --max-warnings 0 \"{src,mock}/**/*.{vue,ts,tsx}\" --fix", "lint:eslint": "eslint --cache --max-warnings 0 \"{src,mock,build}/**/*.{vue,js,ts,tsx}\" --fix",
"lint:prettier": "prettier --write \"src/**/*.{js,json,tsx,css,less,scss,vue,html,md}\"", "lint:prettier": "prettier --write \"src/**/*.{js,ts,json,tsx,css,less,scss,vue,html,md}\"",
"lint:stylelint": "stylelint --cache --fix \"**/*.{vue,css,scss,postcss,less}\" --cache --cache-location node_modules/.cache/stylelint/", "lint:stylelint": "stylelint --cache --fix \"**/*.{vue,css,scss,postcss,less}\" --cache --cache-location node_modules/.cache/stylelint/",
"lint:lint-staged": "lint-staged -c ./.husky/lintstagedrc.js", "lint:lint-staged": "lint-staged -c ./.husky/lintstagedrc.js",
"lint:pretty": "pretty-quick --staged", "lint:pretty": "pretty-quick --staged",
@@ -27,15 +29,18 @@
], ],
"dependencies": { "dependencies": {
"@ctrl/tinycolor": "^3.4.1", "@ctrl/tinycolor": "^3.4.1",
"@pureadmin/components": "^1.0.6", "@pureadmin/components": "^1.1.0",
"@vueuse/core": "^8.4.2", "@pureadmin/descriptions": "^1.1.0",
"@pureadmin/table": "^1.2.0",
"@pureadmin/utils": "^1.1.5",
"@vueuse/core": "^9.4.0",
"@vueuse/motion": "^2.0.0-beta.12", "@vueuse/motion": "^2.0.0-beta.12",
"@vueuse/shared": "^8.4.2", "@vueuse/shared": "^9.4.0",
"animate.css": "^4.1.1", "animate.css": "^4.1.1",
"axios": "^0.27.2", "axios": "^1.1.3",
"css-color-function": "^1.3.3", "dayjs": "^1.11.4",
"dayjs": "^1.11.2", "echarts": "^5.3.3",
"element-plus": "2.1.11", "element-plus": "^2.2.16",
"element-resize-detector": "^1.2.3", "element-resize-detector": "^1.2.3",
"js-cookie": "^3.0.1", "js-cookie": "^3.0.1",
"lodash": "^4.17.21", "lodash": "^4.17.21",
@@ -45,25 +50,25 @@
"mockjs": "^1.1.0", "mockjs": "^1.1.0",
"nprogress": "^0.2.0", "nprogress": "^0.2.0",
"path": "^0.12.7", "path": "^0.12.7",
"pinia": "^2.0.14", "pinia": "^2.0.21",
"qrcode": "^1.5.0", "qs": "^6.11.0",
"qs": "^6.10.2",
"resize-observer-polyfill": "^1.5.1", "resize-observer-polyfill": "^1.5.1",
"responsive-storage": "^1.0.11", "responsive-storage": "^2.1.0",
"rgb-hex": "^4.0.0", "vue": "^3.2.40",
"vue": "^3.2.33", "vue-i18n": "^9.2.2",
"vue-i18n": "^9.2.0-beta.35", "vue-router": "^4.1.6",
"vue-router": "^4.0.15", "vue-types": "^4.2.1",
"vue-types": "^4.1.1" "vxe-table": "^4.3.2",
"xe-utils": "^3.5.6"
}, },
"devDependencies": { "devDependencies": {
"@commitlint/cli": "13.1.0", "@commitlint/cli": "13.1.0",
"@commitlint/config-conventional": "13.1.0", "@commitlint/config-conventional": "13.1.0",
"@iconify-icons/ep": "^1.2.4", "@iconify-icons/ep": "^1.2.7",
"@iconify-icons/ri": "^1.2.1", "@iconify-icons/ri": "^1.2.3",
"@iconify/vue": "^3.2.0", "@iconify/vue": "^3.2.1",
"@intlify/vite-plugin-vue-i18n": "^3.4.0", "@intlify/vite-plugin-vue-i18n": "^6.0.3",
"@pureadmin/theme": "^1.1.0", "@pureadmin/theme": "^2.4.0",
"@types/element-resize-detector": "1.1.3", "@types/element-resize-detector": "1.1.3",
"@types/js-cookie": "^3.0.1", "@types/js-cookie": "^3.0.1",
"@types/lodash": "^4.14.180", "@types/lodash": "^4.14.180",
@@ -71,48 +76,63 @@
"@types/mockjs": "1.0.3", "@types/mockjs": "1.0.3",
"@types/node": "14.14.14", "@types/node": "14.14.14",
"@types/nprogress": "0.2.0", "@types/nprogress": "0.2.0",
"@types/qrcode": "^1.4.2",
"@types/qs": "^6.9.7", "@types/qs": "^6.9.7",
"@typescript-eslint/eslint-plugin": "^5.10.2", "@typescript-eslint/eslint-plugin": "^5.10.2",
"@typescript-eslint/parser": "^5.10.2", "@typescript-eslint/parser": "^5.10.2",
"@vitejs/plugin-legacy": "^1.8.2", "@vitejs/plugin-legacy": "^2.2.0",
"@vitejs/plugin-vue": "^2.3.2", "@vitejs/plugin-vue": "^3.1.2",
"@vitejs/plugin-vue-jsx": "^1.3.10", "@vitejs/plugin-vue-jsx": "^2.0.1",
"@vue/eslint-config-prettier": "^7.0.0", "@vue/eslint-config-prettier": "^7.0.0",
"@vue/eslint-config-typescript": "^10.0.0", "@vue/eslint-config-typescript": "^10.0.0",
"autoprefixer": "^10.4.5", "@vue/runtime-core": "^3.2.40",
"cross-env": "7.0.3", "autoprefixer": "^10.4.12",
"cloc": "^2.10.0",
"cssnano": "^5.1.13",
"eslint": "^8.8.0", "eslint": "^8.8.0",
"eslint-plugin-prettier": "^4.0.0", "eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-vue": "^8.4.1", "eslint-plugin-vue": "^8.4.1",
"husky": "7.0.2", "font-awesome": "^4.7.0",
"husky": "^7.0.4",
"lint-staged": "11.1.2", "lint-staged": "11.1.2",
"picocolors": "^1.0.0", "picocolors": "^1.0.0",
"postcss": "^8.4.6", "postcss": "^8.4.17",
"postcss-html": "^1.3.0", "postcss-html": "^1.5.0",
"postcss-import": "14.0.0", "postcss-import": "^15.0.0",
"postcss-scss": "^4.0.3", "postcss-scss": "^4.0.5",
"prettier": "^2.5.1", "prettier": "^2.5.1",
"pretty-quick": "3.1.1", "pretty-quick": "3.1.1",
"rimraf": "3.0.2", "rimraf": "3.0.2",
"rollup": "^2.70.1", "rollup-plugin-visualizer": "^5.8.2",
"rollup-plugin-visualizer": "^5.6.0", "sass": "^1.53.0",
"sass": "^1.51.0", "sass-loader": "^13.0.2",
"stylelint": "^14.3.0", "stylelint": "^14.3.0",
"stylelint-config-html": "^1.0.0", "stylelint-config-html": "^1.0.0",
"stylelint-config-prettier": "^9.0.3", "stylelint-config-prettier": "^9.0.3",
"stylelint-config-recommended": "^6.0.0", "stylelint-config-recommended": "^6.0.0",
"stylelint-config-standard": "^24.0.0", "stylelint-config-standard": "^24.0.0",
"stylelint-order": "^5.0.0", "stylelint-order": "^5.0.0",
"typescript": "^4.6.3", "tailwindcss": "^3.2.1",
"unocss": "^0.33.2", "terser": "^5.15.0",
"vite": "^2.9.8", "typescript": "^4.7.4",
"unplugin-vue-define-options": "0.7.3",
"vite": "^3.1.8",
"vite-plugin-cdn-import": "^0.3.5",
"vite-plugin-compression": "^0.5.1",
"vite-plugin-mock": "^2.9.6", "vite-plugin-mock": "^2.9.6",
"vite-plugin-remove-console": "^0.0.7", "vite-plugin-remove-console": "^1.1.0",
"vite-svg-loader": "^3.3.0", "vite-svg-loader": "^3.6.0",
"vue-eslint-parser": "^8.2.0" "vue-eslint-parser": "^8.2.0",
"vue-tsc": "^0.40.13"
}, },
"repository": "git@github.com:xiaoxian521/vue-pure-admin.git", "pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"rollup",
"webpack"
]
}
},
"repository": "git@github.com:xiaoxian521/pure-admin-thin.git",
"author": "xiaoxian521", "author": "xiaoxian521",
"license": "MIT" "license": "MIT"
} }

3859
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,8 @@
module.exports = { module.exports = {
plugins: [require("autoprefixer"), require("postcss-import")] plugins: {
"postcss-import": {},
tailwindcss: {},
autoprefixer: {},
...(process.env.NODE_ENV === "production" ? { cssnano: {} } : {})
}
}; };

View File

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

View File

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

View File

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

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 20 KiB

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

@@ -2,12 +2,11 @@ import iconifyIconOffline from "./src/iconifyIconOffline";
import iconifyIconOnline from "./src/iconifyIconOnline"; import iconifyIconOnline from "./src/iconifyIconOnline";
import fontIcon from "./src/iconfont"; import fontIcon from "./src/iconfont";
export const IconifyIconOffline = iconifyIconOffline; /** 离线图标组件 */
export const IconifyIconOnline = iconifyIconOnline; const IconifyIconOffline = iconifyIconOffline;
export const FontIcon = fontIcon; /** 在线图标组件 */
const IconifyIconOnline = iconifyIconOnline;
/** iconfont组件 */
const FontIcon = fontIcon;
export default { export { IconifyIconOffline, IconifyIconOnline, FontIcon };
IconifyIconOffline,
IconifyIconOnline,
FontIcon
};

View File

@@ -1,14 +1,14 @@
import { iconType } from "./types"; import { iconType } from "./types";
import { h, defineComponent, Component } from "vue"; import { h, defineComponent, Component } from "vue";
import { IconifyIconOffline, FontIcon } from "../index"; import { IconifyIconOnline, IconifyIconOffline, FontIcon } from "../index";
/** /**
* 支持fontawesome4、5+、iconfont、remixicon、element-plus的icons、自定义svg * 支持fontawesome4、5+、iconfont、remixicon、element-plus的icons、自定义svg
* @param icon 必传 string 图标 * @param icon 必传 图标
* @param attrs 可选 iconType 属性 * @param attrs 可选 iconType 属性
* @returns Component * @returns Component
*/ */
export function useRenderIcon(icon: string, attrs?: iconType): Component { export function useRenderIcon(icon: any, attrs?: iconType): Component {
// iconfont // iconfont
const ifReg = /^IF-/; const ifReg = /^IF-/;
// typeof icon === "function" 属于SVG // typeof icon === "function" 属于SVG
@@ -30,14 +30,16 @@ export function useRenderIcon(icon: string, attrs?: iconType): Component {
}); });
} }
}); });
} else if (typeof icon === "function") { } else if (typeof icon === "function" || typeof icon?.render === "function") {
// svg // svg
return icon; return icon;
} else { } else {
return defineComponent({ return defineComponent({
name: "Icon", name: "Icon",
render() { render() {
return h(IconifyIconOffline, { const IconifyIcon =
attrs && attrs["online"] ? IconifyIconOnline : IconifyIconOffline;
return h(IconifyIcon, {
icon: icon, icon: icon,
...attrs ...attrs
}); });

View File

@@ -2,7 +2,7 @@ import { h, defineComponent } from "vue";
// 封装iconfont组件默认`font-class`引用模式,支持`unicode`引用、`font-class`引用、`symbol`引用 https://www.iconfont.cn/help/detail?spm=a313x.7781069.1998910419.20&helptype=code // 封装iconfont组件默认`font-class`引用模式,支持`unicode`引用、`font-class`引用、`symbol`引用 https://www.iconfont.cn/help/detail?spm=a313x.7781069.1998910419.20&helptype=code
export default defineComponent({ export default defineComponent({
name: "fontIcon", name: "FontIcon",
props: { props: {
icon: { icon: {
type: String, type: String,

View File

@@ -4,19 +4,17 @@ import { Icon as IconifyIcon, addIcon } from "@iconify/vue/dist/offline";
// element-plus icon // element-plus icon
import Check from "@iconify-icons/ep/check"; import Check from "@iconify-icons/ep/check";
import HomeFilled from "@iconify-icons/ep/home-filled"; import HomeFilled from "@iconify-icons/ep/home-filled";
import Setting from "@iconify-icons/ep/setting";
import Lollipop from "@iconify-icons/ep/lollipop"; import Lollipop from "@iconify-icons/ep/lollipop";
import RefreshRight from "@iconify-icons/ep/refresh-right"; 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 CloseBold from "@iconify-icons/ep/close-bold";
import Bell from "@iconify-icons/ep/bell"; import Bell from "@iconify-icons/ep/bell";
import Search from "@iconify-icons/ep/search"; import Search from "@iconify-icons/ep/search";
addIcon("check", Check); addIcon("check", Check);
addIcon("home-filled", HomeFilled); addIcon("home-filled", HomeFilled);
addIcon("setting", Setting);
addIcon("lollipop", Lollipop); addIcon("lollipop", Lollipop);
addIcon("refresh-right", RefreshRight); addIcon("refresh-right", RefreshRight);
addIcon("arrow-down", ArrowDown); addIcon("close", Close);
addIcon("close-bold", CloseBold); addIcon("close-bold", CloseBold);
addIcon("bell", Bell); addIcon("bell", Bell);
addIcon("search", Search); addIcon("search", Search);
@@ -28,22 +26,42 @@ import LogoutCircleRLine from "@iconify-icons/ri/logout-circle-r-line";
import InformationLine from "@iconify-icons/ri/information-line"; import InformationLine from "@iconify-icons/ri/information-line";
import ArrowUpLine from "@iconify-icons/ri/arrow-up-line"; import ArrowUpLine from "@iconify-icons/ri/arrow-up-line";
import ArrowDownLine from "@iconify-icons/ri/arrow-down-line"; import ArrowDownLine from "@iconify-icons/ri/arrow-down-line";
import Bookmark from "@iconify-icons/ri/bookmark-2-line"; import Bookmark2Line from "@iconify-icons/ri/bookmark-2-line";
import User from "@iconify-icons/ri/user-3-fill"; import User from "@iconify-icons/ri/user-3-fill";
import Lock from "@iconify-icons/ri/lock-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-right-s-line", ArrowRightSLine);
addIcon("arrow-left-s-line", ArrowLeftSLine); addIcon("arrow-left-s-line", ArrowLeftSLine);
addIcon("logout-circle-r-line", LogoutCircleRLine); addIcon("logout-circle-r-line", LogoutCircleRLine);
addIcon("information-line", InformationLine); addIcon("information-line", InformationLine);
addIcon("arrow-up-line", ArrowUpLine); addIcon("arrow-up-line", ArrowUpLine);
addIcon("arrow-down-line", ArrowDownLine); addIcon("arrow-down-line", ArrowDownLine);
addIcon("bookmark", Bookmark); addIcon("bookmark-2-line", Bookmark2Line);
addIcon("user", User); addIcon("user", User);
addIcon("lock", Lock); 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 // Iconify Icon在Vue里离线使用用于内网环境https://docs.iconify.design/icon-components/vue/offline.html
export default defineComponent({ export default defineComponent({
name: "IconifyIcon", name: "IconifyIconOffline",
components: { IconifyIcon }, components: { IconifyIcon },
props: { props: {
icon: { icon: {
@@ -57,6 +75,9 @@ export default defineComponent({
IconifyIcon, IconifyIcon,
{ {
icon: `${this.icon}`, icon: `${this.icon}`,
style: attrs?.style
? Object.assign(attrs.style, { outline: "none" })
: { outline: "none" },
...attrs ...attrs
}, },
{ {

View File

@@ -1,9 +1,9 @@
import { h, defineComponent } from "vue"; import { h, defineComponent } from "vue";
import { Icon as IconifyIcon } from "@iconify/vue"; import { Icon as IconifyIcon } from "@iconify/vue";
// Iconify Icon在Vue里在线使用用于外网环境 https://docs.iconify.design/icon-components/vue/offline.html // Iconify Icon在Vue里在线使用用于外网环境
export default defineComponent({ export default defineComponent({
name: "IconifyIcon", name: "IconifyIconOnline",
components: { IconifyIcon }, components: { IconifyIcon },
props: { props: {
icon: { icon: {
@@ -17,6 +17,9 @@ export default defineComponent({
IconifyIcon, IconifyIcon,
{ {
icon: `${this.icon}`, icon: `${this.icon}`,
style: attrs?.style
? Object.assign(attrs.style, { outline: "none" })
: { outline: "none" },
...attrs ...attrs
}, },
{ {

View File

@@ -11,7 +11,9 @@ export interface iconType {
horizontalAlign?: boolean; horizontalAlign?: boolean;
verticalAlign?: boolean; verticalAlign?: boolean;
align?: string; align?: string;
online?: boolean;
onLoad?: Function; onLoad?: Function;
includes?: Function;
// all icon // all icon
style?: object; style?: object;

View File

@@ -1,12 +0,0 @@
import { App } from "vue";
import reImageVerify from "./src/index.vue";
export const ReImageVerify = Object.assign(reImageVerify, {
install(app: App) {
app.component(reImageVerify.name, reImageVerify);
}
});
export default {
ReImageVerify
};

View File

@@ -1,85 +0,0 @@
import { ref, onMounted } from "vue";
/**
* 绘制图形验证码
* @param width - 图形宽度
* @param height - 图形高度
*/
export const useImageVerify = (width = 120, height = 40) => {
const domRef = ref<HTMLCanvasElement>();
const imgCode = ref("");
function setImgCode(code: string) {
imgCode.value = code;
}
function getImgCode() {
if (!domRef.value) return;
imgCode.value = draw(domRef.value, width, height);
}
onMounted(() => {
getImgCode();
});
return {
domRef,
imgCode,
setImgCode,
getImgCode
};
};
function randomNum(min: number, max: number) {
const num = Math.floor(Math.random() * (max - min) + min);
return num;
}
function randomColor(min: number, max: number) {
const r = randomNum(min, max);
const g = randomNum(min, max);
const b = randomNum(min, max);
return `rgb(${r},${g},${b})`;
}
function draw(dom: HTMLCanvasElement, width: number, height: number) {
let imgCode = "";
const NUMBER_STRING = "0123456789";
const ctx = dom.getContext("2d");
if (!ctx) return imgCode;
ctx.fillStyle = randomColor(180, 230);
ctx.fillRect(0, 0, width, height);
for (let i = 0; i < 4; i += 1) {
const text = NUMBER_STRING[randomNum(0, NUMBER_STRING.length)];
imgCode += text;
const fontSize = randomNum(18, 41);
const deg = randomNum(-30, 30);
ctx.font = `${fontSize}px Simhei`;
ctx.textBaseline = "top";
ctx.fillStyle = randomColor(80, 150);
ctx.save();
ctx.translate(30 * i + 15, 15);
ctx.rotate((deg * Math.PI) / 180);
ctx.fillText(text, -15 + 5, -15);
ctx.restore();
}
for (let i = 0; i < 5; i += 1) {
ctx.beginPath();
ctx.moveTo(randomNum(0, width), randomNum(0, height));
ctx.lineTo(randomNum(0, width), randomNum(0, height));
ctx.strokeStyle = randomColor(180, 230);
ctx.closePath();
ctx.stroke();
}
for (let i = 0; i < 41; i += 1) {
ctx.beginPath();
ctx.arc(randomNum(0, width), randomNum(0, height), 1, 0, 2 * Math.PI);
ctx.closePath();
ctx.fillStyle = randomColor(150, 200);
ctx.fill();
}
return imgCode;
}

View File

@@ -1,48 +0,0 @@
<script lang="ts">
export default {
name: "ReImageVerify"
};
</script>
<script setup lang="ts">
import { watch } from "vue";
import { useImageVerify } from "./hooks";
interface Props {
code?: string;
}
interface Emits {
(e: "update:code", code: string): void;
}
const props = withDefaults(defineProps<Props>(), {
code: ""
});
const emit = defineEmits<Emits>();
const { domRef, imgCode, setImgCode, getImgCode } = useImageVerify();
watch(
() => props.code,
newValue => {
setImgCode(newValue);
}
);
watch(imgCode, newValue => {
emit("update:code", newValue);
});
defineExpose({ getImgCode });
</script>
<template>
<canvas
ref="domRef"
width="120"
height="40"
class="cursor-pointer"
@click="getImgCode"
/>
</template>

View File

@@ -1,10 +0,0 @@
import { App } from "vue";
import reQrcode from "./src/index";
export const ReQrcode = Object.assign(reQrcode, {
install(app: App) {
app.component(reQrcode.name, reQrcode);
}
});
export default ReQrcode;

View File

@@ -1,8 +0,0 @@
.qrcode {
&--disabled {
background: rgba(255, 255, 255, 0.95);
& > div {
transform: translate(-50%, -50%);
}
}
}

View File

@@ -1,262 +0,0 @@
import {
ref,
unref,
watch,
nextTick,
computed,
PropType,
defineComponent
} from "vue";
import "./index.scss";
import { isString } from "/@/utils/is";
import { cloneDeep } from "lodash-unified";
import { propTypes } from "/@/utils/propTypes";
import { IconifyIconOffline } from "../../ReIcon";
import QRCode, { QRCodeRenderersOptions } from "qrcode";
interface QrcodeLogo {
src?: string;
logoSize?: number;
bgColor?: string;
borderSize?: number;
crossOrigin?: string;
borderRadius?: number;
logoRadius?: number;
}
const props = {
// img 或者 canvas,img不支持logo嵌套
tag: propTypes.string
.validate((v: string) => ["canvas", "img"].includes(v))
.def("canvas"),
// 二维码内容
text: {
type: [String, Array] as PropType<string | Recordable[]>,
default: null
},
// qrcode.js配置项
options: {
type: Object as PropType<QRCodeRenderersOptions>,
default: (): QRCodeRenderersOptions => ({})
},
// 宽度
width: propTypes.number.def(200),
// logo
logo: {
type: [String, Object] as PropType<Partial<QrcodeLogo> | string>,
default: (): QrcodeLogo | string => ""
},
// 是否过期
disabled: propTypes.bool.def(false),
// 过期提示内容
disabledText: propTypes.string.def("")
};
export default defineComponent({
name: "ReQrcode",
props,
emits: ["done", "click", "disabled-click"],
setup(props, { emit }) {
const { toCanvas, toDataURL } = QRCode;
const loading = ref(true);
const wrapRef = ref<Nullable<HTMLCanvasElement | HTMLImageElement>>(null);
const renderText = computed(() => String(props.text));
const wrapStyle = computed(() => {
return {
width: props.width + "px",
height: props.width + "px"
};
});
const initQrcode = async () => {
await nextTick();
const options = cloneDeep(props.options || {});
if (props.tag === "canvas") {
// 容错率,默认对内容少的二维码采用高容错率,内容多的二维码采用低容错率
options.errorCorrectionLevel =
options.errorCorrectionLevel ||
getErrorCorrectionLevel(unref(renderText));
const _width: number = await getOriginWidth(unref(renderText), options);
options.scale =
props.width === 0 ? undefined : (props.width / _width) * 4;
const canvasRef: HTMLCanvasElement = await toCanvas(
unref(wrapRef) as HTMLCanvasElement,
unref(renderText),
options
);
if (props.logo) {
const url = await createLogoCode(canvasRef);
emit("done", url);
loading.value = false;
} else {
emit("done", canvasRef.toDataURL());
loading.value = false;
}
} else {
const url = await toDataURL(renderText.value, {
errorCorrectionLevel: "H",
width: props.width,
...options
});
(unref(wrapRef) as HTMLImageElement).src = url;
emit("done", url);
loading.value = false;
}
};
watch(
() => renderText.value,
val => {
if (!val) return;
initQrcode();
},
{
deep: true,
immediate: true
}
);
const createLogoCode = (canvasRef: HTMLCanvasElement) => {
const canvasWidth = canvasRef.width;
const logoOptions: QrcodeLogo = Object.assign(
{
logoSize: 0.15,
bgColor: "#ffffff",
borderSize: 0.05,
crossOrigin: "anonymous",
borderRadius: 8,
logoRadius: 0
},
isString(props.logo) ? {} : props.logo
);
const {
logoSize = 0.15,
bgColor = "#ffffff",
borderSize = 0.05,
crossOrigin = "anonymous",
borderRadius = 8,
logoRadius = 0
} = logoOptions;
const logoSrc = isString(props.logo) ? props.logo : props.logo.src;
const logoWidth = canvasWidth * logoSize;
const logoXY = (canvasWidth * (1 - logoSize)) / 2;
const logoBgWidth = canvasWidth * (logoSize + borderSize);
const logoBgXY = (canvasWidth * (1 - logoSize - borderSize)) / 2;
const ctx = canvasRef.getContext("2d");
if (!ctx) return;
// logo 底色
canvasRoundRect(ctx)(
logoBgXY,
logoBgXY,
logoBgWidth,
logoBgWidth,
borderRadius
);
ctx.fillStyle = bgColor;
ctx.fill();
// logo
const image = new Image();
if (crossOrigin || logoRadius) {
image.setAttribute("crossOrigin", crossOrigin);
}
(image as any).src = logoSrc;
// 使用image绘制可以避免某些跨域情况
const drawLogoWithImage = (image: HTMLImageElement) => {
ctx.drawImage(image, logoXY, logoXY, logoWidth, logoWidth);
};
// 使用canvas绘制以获得更多的功能
const drawLogoWithCanvas = (image: HTMLImageElement) => {
const canvasImage = document.createElement("canvas");
canvasImage.width = logoXY + logoWidth;
canvasImage.height = logoXY + logoWidth;
const imageCanvas = canvasImage.getContext("2d");
if (!imageCanvas || !ctx) return;
imageCanvas.drawImage(image, logoXY, logoXY, logoWidth, logoWidth);
canvasRoundRect(ctx)(logoXY, logoXY, logoWidth, logoWidth, logoRadius);
if (!ctx) return;
const fillStyle = ctx.createPattern(canvasImage, "no-repeat");
if (fillStyle) {
ctx.fillStyle = fillStyle;
ctx.fill();
}
};
// 将 logo绘制到 canvas上
return new Promise((resolve: any) => {
image.onload = () => {
logoRadius ? drawLogoWithCanvas(image) : drawLogoWithImage(image);
resolve(canvasRef.toDataURL());
};
});
};
// 得到原QrCode的大小以便缩放得到正确的QrCode大小
const getOriginWidth = async (
content: string,
options: QRCodeRenderersOptions
) => {
const _canvas = document.createElement("canvas");
await toCanvas(_canvas, content, options);
return _canvas.width;
};
// 对于内容少的QrCode增大容错率
const getErrorCorrectionLevel = (content: string) => {
if (content.length > 36) {
return "M";
} else if (content.length > 16) {
return "Q";
} else {
return "H";
}
};
// 用于绘制圆角
const canvasRoundRect = (ctx: CanvasRenderingContext2D) => {
return (x: number, y: number, w: number, h: number, r: number) => {
const minSize = Math.min(w, h);
if (r > minSize / 2) {
r = minSize / 2;
}
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
return ctx;
};
};
const clickCode = () => {
emit("click");
};
const disabledClick = () => {
emit("disabled-click");
};
return () => (
<>
<div
v-loading={unref(loading)}
class="qrcode relative inline-block"
style={unref(wrapStyle)}
>
{props.tag === "canvas" ? (
<canvas ref={wrapRef} onClick={clickCode}></canvas>
) : (
<img ref={wrapRef} onClick={clickCode}></img>
)}
{props.disabled && (
<div
class="qrcode--disabled absolute top-0 left-0 flex w-full h-full items-center justify-center"
onClick={disabledClick}
>
<div class="absolute top-[50%] left-[50%] font-bold">
<IconifyIconOffline
class="cursor-pointer outline-none"
icon="refresh-right"
width="30"
color="var(--el-color-primary)"
/>
<div>{props.disabledText}</div>
</div>
</div>
)}
</div>
</>
);
}
});

View File

@@ -27,7 +27,7 @@ const getConfig = (key?: string): ServerConfigs => {
return config; return config;
}; };
// 获取项目动态全局配置 /** 获取项目动态全局配置 */
export const getServerConfig = async (app: App): Promise<undefined> => { export const getServerConfig = async (app: App): Promise<undefined> => {
app.config.globalProperties.$config = getConfig(); app.config.globalProperties.$config = getConfig();
return axios({ 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,5 +1,4 @@
import { Directive } from "vue"; import { Directive, type DirectiveBinding, type VNode } from "vue";
import type { DirectiveBinding, VNode } from "vue";
import elementResizeDetectorMaker from "element-resize-detector"; import elementResizeDetectorMaker from "element-resize-detector";
import type { Erd } from "element-resize-detector"; import type { Erd } from "element-resize-detector";
import { emitter } from "/@/utils/mitt"; import { emitter } from "/@/utils/mitt";

View File

@@ -1,2 +1,2 @@
export * from "./permission"; export * from "./auth";
export * from "./elResizeDetector"; 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

@@ -1,23 +1,18 @@
<script setup lang="ts"> <script setup lang="ts">
import { import { useGlobal } from "@pureadmin/utils";
h,
ref,
computed,
Transition,
defineComponent,
getCurrentInstance
} from "vue";
import backTop from "/@/assets/svg/back_top.svg?component"; import backTop from "/@/assets/svg/back_top.svg?component";
import { h, computed, Transition, defineComponent } from "vue";
import { usePermissionStoreHook } from "/@/store/modules/permission"; import { usePermissionStoreHook } from "/@/store/modules/permission";
const props = defineProps({ const props = defineProps({
fixedHeader: Boolean fixedHeader: Boolean
}); });
const keepAlive: Boolean = ref(
getCurrentInstance().appContext.config.globalProperties.$config?.KeepAlive const { $storage, $config } = useGlobal<GlobalPropertiesApi>();
);
const instance = const keepAlive = computed(() => {
getCurrentInstance().appContext.app.config.globalProperties.$storage; return $config?.KeepAlive;
});
const transitions = computed(() => { const transitions = computed(() => {
return route => { return route => {
@@ -26,11 +21,11 @@ const transitions = computed(() => {
}); });
const hideTabs = computed(() => { const hideTabs = computed(() => {
return instance?.configure.hideTabs; return $storage?.configure.hideTabs;
}); });
const layout = computed(() => { const layout = computed(() => {
return instance?.layout.layout === "vertical"; return $storage?.layout.layout === "vertical";
}); });
const getSectionStyle = computed(() => { const getSectionStyle = computed(() => {

View File

@@ -1,101 +1,90 @@
<script setup lang="ts"> <script setup lang="ts">
import { useI18n } from "vue-i18n";
import { useNav } from "../hooks/nav";
import { useRoute } from "vue-router";
import Search from "./search/index.vue"; import Search from "./search/index.vue";
import Notice from "./notice/index.vue"; import Notice from "./notice/index.vue";
import mixNav from "./sidebar/mixNav.vue"; import mixNav from "./sidebar/mixNav.vue";
import avatars from "/@/assets/avatars.jpg"; import avatars from "/@/assets/avatars.jpg";
import Hamburger from "./sidebar/hamBurger.vue"; import { useNav } from "/@/layout/hooks/useNav";
import { watch, getCurrentInstance } from "vue";
import Breadcrumb from "./sidebar/breadCrumb.vue"; import Breadcrumb from "./sidebar/breadCrumb.vue";
import { deviceDetection } from "/@/utils/deviceDetection"; 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"; import globalization from "/@/assets/svg/globalization.svg?component";
const route = useRoute();
const { locale, t } = useI18n();
const instance =
getCurrentInstance().appContext.config.globalProperties.$storage;
const { const {
layout,
device,
logout, logout,
onPanel, onPanel,
changeTitle,
toggleSideBar,
pureApp, pureApp,
username, username,
avatarsStyle, avatarsStyle,
getDropdownItemStyle toggleSideBar,
getDropdownItemStyle,
getDropdownItemClass
} = useNav(); } = useNav();
watch( const { t, locale, translationCh, translationEn } = useTranslationLang();
() => locale.value,
() => {
changeTitle(route.meta);
}
);
function translationCh() {
instance.locale = { locale: "zh" };
locale.value = "zh";
}
function translationEn() {
instance.locale = { locale: "en" };
locale.value = "en";
}
</script> </script>
<template> <template>
<div class="navbar"> <div
<Hamburger class="navbar bg-[#fff] shadow-sm shadow-[rgba(0, 21, 41, 0.08)] dark:shadow-[#0d0d0d]"
v-if="pureApp.layout !== 'mix'" >
:is-active="pureApp.sidebar.opened" <topCollapse
v-if="device === 'mobile'"
class="hamburger-container" class="hamburger-container"
:is-active="pureApp.sidebar.opened"
@toggleClick="toggleSideBar" @toggleClick="toggleSideBar"
/> />
<Breadcrumb v-if="pureApp.layout !== 'mix'" class="breadcrumb-container" /> <Breadcrumb
v-if="layout !== 'mix' && device !== 'mobile'"
class="breadcrumb-container"
/>
<mixNav v-if="pureApp.layout === 'mix'" /> <mixNav v-if="layout === 'mix'" />
<div v-if="pureApp.layout === 'vertical'" class="vertical-header-right"> <div v-if="layout === 'vertical'" class="vertical-header-right">
<!-- 菜单搜索 --> <!-- 菜单搜索 -->
<Search /> <Search />
<!-- 通知 --> <!-- 通知 -->
<Notice id="header-notice" /> <Notice id="header-notice" />
<!-- 全屏 -->
<screenfull id="header-screenfull" v-show="!deviceDetection()" />
<!-- 国际化 --> <!-- 国际化 -->
<el-dropdown id="header-translation" trigger="click"> <el-dropdown id="header-translation" trigger="click">
<globalization /> <globalization
class="navbar-bg-hover w-[40px] h-[48px] p-[11px] cursor-pointer outline-none"
/>
<template #dropdown> <template #dropdown>
<el-dropdown-menu class="translation"> <el-dropdown-menu class="translation">
<el-dropdown-item <el-dropdown-item
:style="getDropdownItemStyle(locale, 'zh')" :style="getDropdownItemStyle(locale, 'zh')"
:class="['dark:!text-white', getDropdownItemClass(locale, 'zh')]"
@click="translationCh" @click="translationCh"
><IconifyIconOffline >
<IconifyIconOffline
class="check-zh" class="check-zh"
v-show="locale === 'zh'" v-show="locale === 'zh'"
icon="check" icon="check"
/>简体中文</el-dropdown-item />
> 简体中文
</el-dropdown-item>
<el-dropdown-item <el-dropdown-item
:style="getDropdownItemStyle(locale, 'en')" :style="getDropdownItemStyle(locale, 'en')"
:class="['dark:!text-white', getDropdownItemClass(locale, 'en')]"
@click="translationEn" @click="translationEn"
> >
<span class="check-en" v-show="locale === 'en'"> <span class="check-en" v-show="locale === 'en'">
<IconifyIconOffline icon="check" /> </span <IconifyIconOffline icon="check" />
>English </span>
English
</el-dropdown-item> </el-dropdown-item>
</el-dropdown-menu> </el-dropdown-menu>
</template> </template>
</el-dropdown> </el-dropdown>
<!-- 退出登 --> <!-- 退出登 -->
<el-dropdown trigger="click"> <el-dropdown trigger="click">
<span class="el-dropdown-link"> <span class="el-dropdown-link navbar-bg-hover">
<img v-if="avatars" :src="avatars" :style="avatarsStyle" /> <img v-if="avatars" :src="avatars" :style="avatarsStyle" />
<p v-if="username">{{ username }}</p> <p v-if="username" class="dark:text-white">{{ username }}</p>
</span> </span>
<template #dropdown> <template #dropdown>
<el-dropdown-menu class="logout"> <el-dropdown-menu class="logout">
@@ -103,13 +92,14 @@ function translationEn() {
<IconifyIconOffline <IconifyIconOffline
icon="logout-circle-r-line" icon="logout-circle-r-line"
style="margin: 5px" style="margin: 5px"
/>{{ t("buttons.hsLoginOut") }}</el-dropdown-item />
> {{ t("buttons.hsLoginOut") }}
</el-dropdown-item>
</el-dropdown-menu> </el-dropdown-menu>
</template> </template>
</el-dropdown> </el-dropdown>
<span <span
class="el-icon-setting" class="set-icon navbar-bg-hover"
:title="t('buttons.hssystemSet')" :title="t('buttons.hssystemSet')"
@click="onPanel" @click="onPanel"
> >
@@ -124,16 +114,12 @@ function translationEn() {
width: 100%; width: 100%;
height: 48px; height: 48px;
overflow: hidden; overflow: hidden;
background: #fff;
box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
.hamburger-container { .hamburger-container {
line-height: 48px; line-height: 48px;
height: 100%; height: 100%;
float: left; float: left;
cursor: pointer; cursor: pointer;
transition: background 0.3s;
-webkit-tap-highlight-color: transparent;
} }
.vertical-header-right { .vertical-header-right {
@@ -144,31 +130,6 @@ function translationEn() {
color: #000000d9; color: #000000d9;
justify-content: flex-end; justify-content: flex-end;
:deep(.dropdown-badge) {
&:hover {
background: #f6f6f6;
}
}
.screen-full {
cursor: pointer;
&:hover {
background: #f6f6f6;
}
}
.globalization {
height: 48px;
width: 40px;
padding: 11px;
cursor: pointer;
&:hover {
background: #f6f6f6;
}
}
.el-dropdown-link { .el-dropdown-link {
height: 48px; height: 48px;
padding: 10px; padding: 10px;
@@ -178,10 +139,6 @@ function translationEn() {
cursor: pointer; cursor: pointer;
color: #000000d9; color: #000000d9;
&:hover {
background: #f6f6f6;
}
p { p {
font-size: 14px; font-size: 14px;
} }
@@ -192,23 +149,11 @@ function translationEn() {
border-radius: 50%; border-radius: 50%;
} }
} }
.el-icon-setting {
height: 48px;
width: 38px;
padding: 12px;
display: flex;
cursor: pointer;
align-items: center;
&:hover {
background: #f6f6f6;
}
}
} }
.breadcrumb-container { .breadcrumb-container {
float: left; float: left;
margin-left: 16px;
} }
} }

View File

@@ -15,14 +15,13 @@ notices.value.forEach(notice => {
}); });
function tabClick() { function tabClick() {
// @ts-expect-error (dropdownDom as any).value.handleOpen();
dropdownDom.value.handleOpen();
} }
</script> </script>
<template> <template>
<el-dropdown ref="dropdownDom" trigger="click" placement="bottom-end"> <el-dropdown ref="dropdownDom" trigger="click" placement="bottom-end">
<span class="dropdown-badge"> <span class="dropdown-badge navbar-bg-hover select-none">
<el-badge :value="noticesNum" :max="99"> <el-badge :value="noticesNum" :max="99">
<span class="header-notice-icon"> <span class="header-notice-icon">
<IconifyIconOffline icon="bell" /> <IconifyIconOffline icon="bell" />

View File

@@ -44,7 +44,9 @@ function hoverDescription(event, description) {
</script> </script>
<template> <template>
<div class="notice-container"> <div
class="notice-container border-b-[1px] border-solid border-[#f0f0f0] dark:border-[#303030]"
>
<el-avatar <el-avatar
v-if="props.noticeItem.avatar" v-if="props.noticeItem.avatar"
:size="30" :size="30"
@@ -52,7 +54,7 @@ function hoverDescription(event, description) {
class="notice-container-avatar" class="notice-container-avatar"
/> />
<div class="notice-container-text"> <div class="notice-container-text">
<div class="notice-text-title"> <div class="notice-text-title text-[#000000d9] dark:text-white">
<el-tooltip <el-tooltip
popper-class="notice-title-popper" popper-class="notice-title-popper"
:disabled="!titleTooltip" :disabled="!titleTooltip"
@@ -72,7 +74,8 @@ function hoverDescription(event, description) {
:type="props.noticeItem?.status" :type="props.noticeItem?.status"
size="small" size="small"
class="notice-title-extra" class="notice-title-extra"
>{{ props.noticeItem?.extra }} >
{{ props.noticeItem?.extra }}
</el-tag> </el-tag>
</div> </div>
@@ -90,7 +93,7 @@ function hoverDescription(event, description) {
{{ props.noticeItem.description }} {{ props.noticeItem.description }}
</div> </div>
</el-tooltip> </el-tooltip>
<div class="notice-text-datetime"> <div class="notice-text-datetime text-[#00000073] dark:text-white">
{{ props.noticeItem.datetime }} {{ props.noticeItem.datetime }}
</div> </div>
</div> </div>
@@ -108,7 +111,7 @@ function hoverDescription(event, description) {
align-items: flex-start; align-items: flex-start;
justify-content: space-between; justify-content: space-between;
padding: 12px 0; padding: 12px 0;
border-bottom: 1px solid #f0f0f0; // border-bottom: 1px solid #f0f0f0;
.notice-container-avatar { .notice-container-avatar {
margin-right: 16px; margin-right: 16px;
@@ -127,7 +130,6 @@ function hoverDescription(event, description) {
font-weight: 400; font-weight: 400;
font-size: 14px; font-size: 14px;
line-height: 1.5715; line-height: 1.5715;
color: rgba(0, 0, 0, 0.85);
cursor: pointer; cursor: pointer;
.notice-title-content { .notice-title-content {
@@ -149,7 +151,6 @@ function hoverDescription(event, description) {
.notice-text-datetime { .notice-text-datetime {
font-size: 12px; font-size: 12px;
line-height: 1.5715; line-height: 1.5715;
color: rgba(0, 0, 0, 0.45);
} }
.notice-text-description { .notice-text-description {

View File

@@ -5,7 +5,7 @@ import { emitter } from "/@/utils/mitt";
let show = ref<Boolean>(false); let show = ref<Boolean>(false);
const target = ref(null); const target = ref(null);
onClickOutside(target, event => { onClickOutside(target, (event: any) => {
if (event.clientX > target.value.offsetLeft) return; if (event.clientX > target.value.offsetLeft) return;
show.value = false; show.value = false;
}); });
@@ -18,15 +18,21 @@ emitter.on("openPanel", () => {
<template> <template>
<div :class="{ show: show }" class="right-panel-container"> <div :class="{ show: show }" class="right-panel-container">
<div class="right-panel-background" /> <div class="right-panel-background" />
<div ref="target" class="right-panel"> <div ref="target" class="right-panel bg-bg_color">
<div class="right-panel-items"> <div class="right-panel-items">
<div class="project-configuration"> <div class="project-configuration">
<h3>项目配置</h3> <h3 class="dark:text-white">项目配置</h3>
<el-icon title="关闭配置" class="el-icon-close" @click="show = !show"> <span title="关闭配置">
<IconifyIconOffline icon="close-bold" /> <IconifyIconOffline
</el-icon> class="dark:text-white"
icon="close"
@click="show = !show"
/>
</span>
</div> </div>
<div style="border-bottom: 1px solid #dcdfe6" /> <div
class="border-b-[1px] border-solid border-[#dcdfe6] dark:border-[#303030]"
/>
<slot /> <slot />
</div> </div>
</div> </div>
@@ -62,7 +68,7 @@ emitter.on("openPanel", () => {
box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.05); box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.05);
transition: all 0.25s cubic-bezier(0.7, 0.3, 0.1, 1); transition: all 0.25s cubic-bezier(0.7, 0.3, 0.1, 1);
transform: translate(100%); transform: translate(100%);
background: #fff; // background: #fff;
z-index: 40000; z-index: 40000;
} }
@@ -119,8 +125,8 @@ emitter.on("openPanel", () => {
top: 15px; top: 15px;
margin-left: 10px; margin-left: 10px;
i { svg {
font-size: 16px; font-size: 20px;
margin-right: 20px; margin-right: 20px;
&:hover { &:hover {

View File

@@ -1,13 +1,16 @@
<script setup lang="ts"> <script setup lang="ts">
import { useFullscreen } from "@vueuse/core";
import { useI18n } from "vue-i18n"; import { useI18n } from "vue-i18n";
import { useFullscreen } from "@vueuse/core";
const { t } = useI18n(); const { t } = useI18n();
const { isFullscreen, toggle } = useFullscreen(); const { isFullscreen, toggle } = useFullscreen();
</script> </script>
<template> <template>
<div class="screen-full" @click="toggle"> <div
class="screen-full w-[36px] h-[48px] flex-ac cursor-pointer navbar-bg-hover"
@click="toggle"
>
<FontIcon <FontIcon
:title=" :title="
isFullscreen ? t('buttons.hsexitfullscreen') : t('buttons.hsfullscreen') isFullscreen ? t('buttons.hsexitfullscreen') : t('buttons.hsfullscreen')
@@ -16,13 +19,3 @@ const { isFullscreen, toggle } = useFullscreen();
/> />
</div> </div>
</template> </template>
<style lang="scss" scoped>
.screen-full {
width: 36px;
height: 48px;
display: flex;
align-items: center;
justify-content: space-around;
}
</style>

View File

@@ -1,5 +1,5 @@
<template> <template>
<div class="search-footer"> <div class="search-footer text-[#333] dark:text-white">
<span class="search-footer-item"> <span class="search-footer-item">
<enterOutlined class="icon" /> <enterOutlined class="icon" />
确认 确认
@@ -23,7 +23,6 @@ import mdiKeyboardEsc from "/@/assets/svg/mdi_keyboard_esc.svg?component";
<style lang="scss" scoped> <style lang="scss" scoped>
.search-footer { .search-footer {
display: flex; display: flex;
color: #333;
.search-footer-item { .search-footer-item {
display: flex; display: flex;

View File

@@ -1,9 +1,11 @@
<script lang="ts" setup> <script lang="ts" setup>
import { useRouter } from "vue-router"; import { useRouter } from "vue-router";
import { cloneDeep } from "lodash-unified";
import SearchResult from "./SearchResult.vue"; import SearchResult from "./SearchResult.vue";
import SearchFooter from "./SearchFooter.vue"; import SearchFooter from "./SearchFooter.vue";
import { deleteChildren } from "/@/utils/tree"; import { useNav } from "/@/layout/hooks/useNav";
import { transformI18n } from "/@/plugins/i18n"; import { transformI18n } from "/@/plugins/i18n";
import { deleteChildren } from "@pureadmin/utils";
import { useDebounceFn, onKeyStroke } from "@vueuse/core"; import { useDebounceFn, onKeyStroke } from "@vueuse/core";
import { ref, watch, computed, nextTick, shallowRef } from "vue"; import { ref, watch, computed, nextTick, shallowRef } from "vue";
import { usePermissionStoreHook } from "/@/store/modules/permission"; import { usePermissionStoreHook } from "/@/store/modules/permission";
@@ -17,6 +19,7 @@ interface Emits {
(e: "update:value", val: boolean): void; (e: "update:value", val: boolean): void;
} }
const { device } = useNav();
const emit = defineEmits<Emits>(); const emit = defineEmits<Emits>();
const props = withDefaults(defineProps<Props>(), {}); const props = withDefaults(defineProps<Props>(), {});
const router = useRouter(); const router = useRouter();
@@ -29,7 +32,7 @@ const handleSearch = useDebounceFn(search, 300);
/** 菜单树形结构 */ /** 菜单树形结构 */
const menusData = computed(() => { const menusData = computed(() => {
return deleteChildren(usePermissionStoreHook().menusTree); return deleteChildren(cloneDeep(usePermissionStoreHook().wholeMenus));
}); });
const show = computed({ const show = computed({
@@ -130,7 +133,12 @@ onKeyStroke("ArrowDown", handleDown);
</script> </script>
<template> <template>
<el-dialog top="5vh" v-model="show" :before-close="handleClose"> <el-dialog
top="5vh"
:width="device === 'mobile' ? '80vw' : '50vw'"
v-model="show"
:before-close="handleClose"
>
<el-input <el-input
ref="inputRef" ref="inputRef"
v-model="keyword" v-model="keyword"

View File

@@ -1,24 +1,3 @@
<template>
<div class="result">
<template v-for="item in options" :key="item.path">
<div
class="result-item"
:style="{
background:
item?.path === active ? useEpThemeStoreHook().epThemeColor : '',
color: item.path === active ? '#fff' : ''
}"
@click="handleTo"
@mouseenter="handleMouse(item)"
>
<component :is="useRenderIcon(item.meta?.icon ?? 'bookmark')" />
<span class="result-item-title">{{ t(item.meta?.title) }}</span>
<enterOutlined />
</div>
</template>
</div>
</template>
<script lang="ts" setup> <script lang="ts" setup>
import { computed } from "vue"; import { computed } from "vue";
import { useI18n } from "vue-i18n"; import { useI18n } from "vue-i18n";
@@ -49,6 +28,17 @@ interface Emits {
const props = withDefaults(defineProps<Props>(), {}); const props = withDefaults(defineProps<Props>(), {});
const emit = defineEmits<Emits>(); const emit = defineEmits<Emits>();
const itemStyle = computed(() => {
return item => {
return {
background:
item?.path === active.value ? useEpThemeStoreHook().epThemeColor : "",
color: item.path === active.value ? "#fff" : "",
fontSize: item.path === active.value ? "16px" : "14px"
};
};
});
const active = computed({ const active = computed({
get() { get() {
return props.value; return props.value;
@@ -67,6 +57,24 @@ function handleTo() {
emit("enter"); emit("enter");
} }
</script> </script>
<template>
<div class="result">
<template v-for="item in options" :key="item.path">
<div
class="result-item dark:bg-[#1d1d1d]"
:style="itemStyle(item)"
@click="handleTo"
@mouseenter="handleMouse(item)"
>
<component :is="useRenderIcon(item.meta?.icon ?? 'bookmark-2-line')" />
<span class="result-item-title">{{ t(item.meta?.title) }}</span>
<enterOutlined />
</div>
</template>
</div>
</template>
<style lang="scss" scoped> <style lang="scss" scoped>
.result { .result {
padding-bottom: 12px; padding-bottom: 12px;
@@ -78,8 +86,9 @@ function handleTo() {
margin-top: 8px; margin-top: 8px;
padding: 14px; padding: 14px;
border-radius: 4px; border-radius: 4px;
background: #e5e7eb;
cursor: pointer; cursor: pointer;
border: 0.1px solid #ccc;
transition: all 0.3s;
&-title { &-title {
display: flex; display: flex;

View File

@@ -1,6 +1,6 @@
<script lang="ts" setup> <script lang="ts" setup>
import { SearchModal } from "./components"; import { SearchModal } from "./components";
import useBoolean from "../../hooks/useBoolean"; import { useBoolean } from "../../hooks/useBoolean";
const { bool: show, toggle } = useBoolean(); const { bool: show, toggle } = useBoolean();
function handleSearch() { function handleSearch() {
toggle(); toggle();
@@ -8,23 +8,11 @@ function handleSearch() {
</script> </script>
<template> <template>
<div class="search-container" @click="handleSearch"> <div
class="search-container w-[40px] h-[48px] flex-c cursor-pointer navbar-bg-hover"
@click="handleSearch"
>
<IconifyIconOffline icon="search" /> <IconifyIconOffline icon="search" />
</div> </div>
<SearchModal v-model:value="show" /> <SearchModal v-model:value="show" />
</template> </template>
<style lang="scss" scoped>
.search-container {
display: flex;
align-items: center;
justify-content: center;
height: 48px;
width: 40px;
cursor: pointer;
&:hover {
background: #f6f6f6;
}
}
</style>

View File

@@ -1,75 +1,58 @@
<script setup lang="ts"> <script setup lang="ts">
import { import {
reactive,
ref, ref,
unref, unref,
watch, watch,
reactive,
computed, computed,
nextTick, nextTick,
useCssModule, useCssModule
getCurrentInstance
} from "vue"; } from "vue";
import { find } from "lodash-unified";
import { getConfig } from "/@/config"; import { getConfig } from "/@/config";
import { useRouter } from "vue-router"; import { useRouter } from "vue-router";
import panel from "../panel/index.vue"; import panel from "../panel/index.vue";
import { emitter } from "/@/utils/mitt"; import { emitter } from "/@/utils/mitt";
import { resetRouter } from "/@/router";
import { templateRef } from "@vueuse/core"; import { templateRef } from "@vueuse/core";
import { debounce } from "/@/utils/debounce"; import { removeToken } from "/@/utils/auth";
import { themeColorsType } from "../../types"; import { routerArrays } from "/@/layout/types";
import { useNav } from "/@/layout/hooks/useNav";
import { useAppStoreHook } from "/@/store/modules/app"; import { useAppStoreHook } from "/@/store/modules/app";
import { shadeBgColor } from "../../theme/element-plus";
import { useEpThemeStoreHook } from "/@/store/modules/epTheme";
import { storageLocal, storageSession } from "/@/utils/storage";
import { useMultiTagsStoreHook } from "/@/store/modules/multiTags"; import { useMultiTagsStoreHook } from "/@/store/modules/multiTags";
import { createNewStyle, writeNewStyle } from "../../theme/element-plus"; import { useDataThemeChange } from "/@/layout/hooks/useDataThemeChange";
import {
useDark,
debounce,
useGlobal,
storageLocal,
storageSession
} from "@pureadmin/utils";
import { toggleTheme } from "@pureadmin/theme/dist/browser-utils"; import { toggleTheme } from "@pureadmin/theme/dist/browser-utils";
import dayIcon from "/@/assets/svg/day.svg?component"; import dayIcon from "/@/assets/svg/day.svg?component";
import darkIcon from "/@/assets/svg/dark.svg?component"; import darkIcon from "/@/assets/svg/dark.svg?component";
const router = useRouter(); const router = useRouter();
const { device } = useNav();
const { isDark } = useDark();
const { isSelect } = useCssModule(); const { isSelect } = useCssModule();
const body = document.documentElement as HTMLElement; const { $storage } = useGlobal<GlobalPropertiesApi>();
const instance =
getCurrentInstance().appContext.app.config.globalProperties.$storage;
const instanceConfig =
getCurrentInstance().appContext.app.config.globalProperties.$config;
let themeColors = ref<Array<themeColorsType>>([
// 道奇蓝(默认)
{ color: "#1b2a47", themeColor: "default" },
// 亮白色
{ color: "#ffffff", themeColor: "light" },
// 猩红色
{ color: "#f5222d", themeColor: "dusk" },
// 橙红色
{ color: "#fa541c", themeColor: "volcano" },
// 金色
{ color: "#fadb14", themeColor: "yellow" },
// 绿宝石
{ color: "#13c2c2", themeColor: "mingQing" },
// 酸橙绿
{ color: "#52c41a", themeColor: "auroraGreen" },
// 深粉色
{ color: "#eb2f96", themeColor: "pink" },
// 深紫罗兰色
{ color: "#722ed1", themeColor: "saucePurple" }
]);
const mixRef = templateRef<HTMLElement | null>("mixRef", null);
const verticalRef = templateRef<HTMLElement | null>("verticalRef", null); const verticalRef = templateRef<HTMLElement | null>("verticalRef", null);
const horizontalRef = templateRef<HTMLElement | null>("horizontalRef", null); const horizontalRef = templateRef<HTMLElement | null>("horizontalRef", null);
const mixRef = templateRef<HTMLElement | null>("mixRef", null);
let layoutTheme = const {
ref(storageLocal.getItem("responsive-layout")) || body,
ref({ dataTheme,
layout: instanceConfig?.Layout ?? "vertical", layoutTheme,
theme: instanceConfig?.Theme ?? "default" themeColors,
}); dataThemeChange,
setEpThemeColor,
setLayoutThemeColor
} = useDataThemeChange();
// body添加layout属性作用于src/style/sidebar.scss /* body添加layout属性作用于src/style/sidebar.scss */
if (unref(layoutTheme)) { if (unref(layoutTheme)) {
let layout = unref(layoutTheme).layout; let layout = unref(layoutTheme).layout;
let theme = unref(layoutTheme).theme; let theme = unref(layoutTheme).theme;
@@ -79,20 +62,18 @@ if (unref(layoutTheme)) {
setLayoutModel(layout); setLayoutModel(layout);
} }
// 默认灵动模式 /** 默认灵动模式 */
const markValue = ref(instance.configure?.showModel ?? "smart"); const markValue = ref($storage.configure?.showModel ?? "smart");
const logoVal = ref(instance.configure?.showLogo ?? true); const logoVal = ref($storage.configure?.showLogo ?? true);
const epThemeColor = ref(useEpThemeStoreHook().getEpThemeColor);
const settings = reactive({ const settings = reactive({
greyVal: instance.configure.grey, greyVal: $storage.configure.grey,
weakVal: instance.configure.weak, weakVal: $storage.configure.weak,
tabsVal: instance.configure.hideTabs, tabsVal: $storage.configure.hideTabs,
showLogo: instance.configure.showLogo, showLogo: $storage.configure.showLogo,
showModel: instance.configure.showModel, showModel: $storage.configure.showModel,
multiTagsCache: instance.configure.multiTagsCache multiTagsCache: $storage.configure.multiTagsCache
}); });
const getThemeColorStyle = computed(() => { const getThemeColorStyle = computed(() => {
@@ -101,10 +82,17 @@ const getThemeColorStyle = computed(() => {
}; };
}); });
/** 当网页为暗黑模式时不显示亮白色切换选项 */
const showThemeColors = computed(() => {
return themeColor => {
return themeColor === "light" && isDark.value ? false : true;
};
});
function storageConfigureChange<T>(key: string, val: T): void { function storageConfigureChange<T>(key: string, val: T): void {
const storageConfigure = instance.configure; const storageConfigure = $storage.configure;
storageConfigure[key] = val; storageConfigure[key] = val;
instance.configure = storageConfigure; $storage.configure = storageConfigure;
} }
function toggleClass(flag: boolean, clsName: string, target?: HTMLElement) { function toggleClass(flag: boolean, clsName: string, target?: HTMLElement) {
@@ -114,13 +102,13 @@ function toggleClass(flag: boolean, clsName: string, target?: HTMLElement) {
targetEl.className = flag ? `${className} ${clsName} ` : className; targetEl.className = flag ? `${className} ${clsName} ` : className;
} }
// 灰色模式设置 /** 灰色模式设置 */
const greyChange = (value): void => { const greyChange = (value): void => {
toggleClass(settings.greyVal, "html-grey", document.querySelector("html")); toggleClass(settings.greyVal, "html-grey", document.querySelector("html"));
storageConfigureChange("grey", value); storageConfigureChange("grey", value);
}; };
// 色弱模式设置 /** 色弱模式设置 */
const weekChange = (value): void => { const weekChange = (value): void => {
toggleClass( toggleClass(
settings.weakVal, settings.weakVal,
@@ -133,7 +121,7 @@ const weekChange = (value): void => {
const tagsChange = () => { const tagsChange = () => {
let showVal = settings.tabsVal; let showVal = settings.tabsVal;
storageConfigureChange("hideTabs", showVal); storageConfigureChange("hideTabs", showVal);
emitter.emit("tagViewsChange", showVal); emitter.emit("tagViewsChange", showVal as unknown as string);
}; };
const multiTagsCacheChange = () => { const multiTagsCacheChange = () => {
@@ -142,27 +130,20 @@ const multiTagsCacheChange = () => {
useMultiTagsStoreHook().multiTagsCacheChange(multiTagsCache); useMultiTagsStoreHook().multiTagsCacheChange(multiTagsCache);
}; };
// 清空缓存并返回登录页 /** 清空缓存并返回登录页 */
function onReset() { function onReset() {
router.push("/login"); removeToken();
storageLocal.clear();
storageSession.clear();
const { Grey, Weak, MultiTagsCache, EpThemeColor, Layout } = getConfig(); const { Grey, Weak, MultiTagsCache, EpThemeColor, Layout } = getConfig();
useAppStoreHook().setLayout(Layout); useAppStoreHook().setLayout(Layout);
useEpThemeStoreHook().setEpThemeColor(EpThemeColor); setEpThemeColor(EpThemeColor);
useMultiTagsStoreHook().multiTagsCacheChange(MultiTagsCache); useMultiTagsStoreHook().multiTagsCacheChange(MultiTagsCache);
toggleClass(Grey, "html-grey", document.querySelector("html")); toggleClass(Grey, "html-grey", document.querySelector("html"));
toggleClass(Weak, "html-weakness", document.querySelector("html")); toggleClass(Weak, "html-weakness", document.querySelector("html"));
useMultiTagsStoreHook().handleTags("equal", [ router.push("/login");
{ useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
path: "/welcome", resetRouter();
parentPath: "/",
meta: {
title: "menus.hshome",
icon: "home-filled"
}
}
]);
storageLocal.clear();
storageSession.clear();
} }
function onChange(label) { function onChange(label) {
@@ -170,7 +151,7 @@ function onChange(label) {
emitter.emit("tagViewsShowModel", label); emitter.emit("tagViewsShowModel", label);
} }
// 侧边栏Logo /** 侧边栏Logo */
function logoChange() { function logoChange() {
unref(logoVal) unref(logoVal)
? storageConfigureChange("showLogo", true) ? storageConfigureChange("showLogo", true)
@@ -184,7 +165,9 @@ function setFalse(Doms): any {
}); });
} }
watch(instance, ({ layout }) => { watch($storage, ({ layout }) => {
/* 设置wangeditorV5主题色 */
body.style.setProperty("--w-e-toolbar-active-color", layout["epThemeColor"]);
switch (layout["layout"]) { switch (layout["layout"]) {
case "vertical": case "vertical":
toggleClass(true, isSelect, unref(verticalRef)); toggleClass(true, isSelect, unref(verticalRef));
@@ -204,7 +187,7 @@ watch(instance, ({ layout }) => {
} }
}); });
// 主题色 激活选择项 /** 主题色 激活选择项 */
const getThemeColor = computed(() => { const getThemeColor = computed(() => {
return current => { return current => {
if ( if (
@@ -223,83 +206,27 @@ const getThemeColor = computed(() => {
}; };
}); });
// 设置导航模式 /** 设置导航模式 */
function setLayoutModel(layout: string) { function setLayoutModel(layout: string) {
layoutTheme.value.layout = layout; layoutTheme.value.layout = layout;
window.document.body.setAttribute("layout", layout); window.document.body.setAttribute("layout", layout);
instance.layout = { $storage.layout = {
layout, layout,
theme: layoutTheme.value.theme, theme: layoutTheme.value.theme,
darkMode: instance.layout.darkMode, darkMode: $storage.layout?.darkMode,
sidebarStatus: instance.layout.sidebarStatus, sidebarStatus: $storage.layout?.sidebarStatus,
epThemeColor: instance.layout.epThemeColor epThemeColor: $storage.layout?.epThemeColor
}; };
useAppStoreHook().setLayout(layout); useAppStoreHook().setLayout(layout);
} }
// 存放夜间主题切换前的导航主题色 /* 初始化项目配置 */
let tempLayoutThemeColor;
// 设置导航主题色
function setLayoutThemeColor(theme: string) {
tempLayoutThemeColor = instance.layout.theme;
layoutTheme.value.theme = theme;
toggleTheme({
scopeName: `layout-theme-${theme}`
});
instance.layout = {
layout: useAppStoreHook().layout,
theme,
darkMode: dataTheme.value,
sidebarStatus: instance.layout.sidebarStatus,
epThemeColor: instance.layout.epThemeColor
};
if (theme === "default" || theme === "light") {
setEpThemeColor(getConfig().EpThemeColor);
} else {
const colors = find(themeColors.value, { themeColor: theme });
setEpThemeColor(colors.color);
}
}
// 设置ep主题色
const setEpThemeColor = (color: string) => {
// @ts-expect-error
writeNewStyle(createNewStyle(color));
useEpThemeStoreHook().setEpThemeColor(color);
body.style.setProperty("--el-color-primary-active", shadeBgColor(color));
};
let dataTheme = ref<boolean>(instance.layout.darkMode);
// 日间、夜间主题切换
function dataThemeChange() {
if (dataTheme.value) {
body.setAttribute("data-theme", "dark");
setLayoutThemeColor("light");
} else {
body.setAttribute("data-theme", "");
tempLayoutThemeColor && setLayoutThemeColor(tempLayoutThemeColor);
instance.layout = {
layout: useAppStoreHook().layout,
theme: instance.layout.theme,
darkMode: dataTheme.value,
sidebarStatus: instance.layout.sidebarStatus,
epThemeColor: instance.layout.epThemeColor
};
}
}
//初始化项目配置
nextTick(() => { nextTick(() => {
settings.greyVal && settings.greyVal &&
document.querySelector("html")?.setAttribute("class", "html-grey"); document.querySelector("html")?.setAttribute("class", "html-grey");
settings.weakVal && settings.weakVal &&
document.querySelector("html")?.setAttribute("class", "html-weakness"); document.querySelector("html")?.setAttribute("class", "html-weakness");
settings.tabsVal && tagsChange(); settings.tabsVal && tagsChange();
// @ts-expect-error
writeNewStyle(createNewStyle(epThemeColor.value));
dataThemeChange(); dataThemeChange();
}); });
</script> </script>
@@ -329,7 +256,12 @@ nextTick(() => {
</li> </li>
</el-tooltip> </el-tooltip>
<el-tooltip class="item" content="顶部模式" placement="bottom"> <el-tooltip
v-if="device !== 'mobile'"
class="item"
content="顶部模式"
placement="bottom"
>
<li <li
:class="layoutTheme.layout === 'horizontal' ? $style.isSelect : ''" :class="layoutTheme.layout === 'horizontal' ? $style.isSelect : ''"
ref="horizontalRef" ref="horizontalRef"
@@ -340,7 +272,12 @@ nextTick(() => {
</li> </li>
</el-tooltip> </el-tooltip>
<el-tooltip class="item" content="混合模式" placement="bottom"> <el-tooltip
v-if="device !== 'mobile'"
class="item"
content="混合模式"
placement="bottom"
>
<li <li
:class="layoutTheme.layout === 'mix' ? $style.isSelect : ''" :class="layoutTheme.layout === 'mix' ? $style.isSelect : ''"
ref="mixRef" ref="mixRef"
@@ -352,11 +289,12 @@ nextTick(() => {
</el-tooltip> </el-tooltip>
</ul> </ul>
<el-divider v-show="!dataTheme">主题色</el-divider> <el-divider>主题色</el-divider>
<ul class="theme-color" v-show="!dataTheme"> <ul class="theme-color">
<li <li
v-for="(item, index) in themeColors" v-for="(item, index) in themeColors"
:key="index" :key="index"
v-show="showThemeColors(item.themeColor)"
:style="getThemeColorStyle(item.color)" :style="getThemeColorStyle(item.color)"
@click="setLayoutThemeColor(item.themeColor)" @click="setLayoutThemeColor(item.themeColor)"
> >
@@ -372,8 +310,8 @@ nextTick(() => {
<el-divider>界面显示</el-divider> <el-divider>界面显示</el-divider>
<ul class="setting"> <ul class="setting">
<li v-show="!dataTheme"> <li>
<span>灰色模式</span> <span class="dark:text-white">灰色模式</span>
<el-switch <el-switch
v-model="settings.greyVal" v-model="settings.greyVal"
inline-prompt inline-prompt
@@ -383,8 +321,8 @@ nextTick(() => {
@change="greyChange" @change="greyChange"
/> />
</li> </li>
<li v-show="!dataTheme"> <li>
<span>色弱模式</span> <span class="dark:text-white">色弱模式</span>
<el-switch <el-switch
v-model="settings.weakVal" v-model="settings.weakVal"
inline-prompt inline-prompt
@@ -395,7 +333,7 @@ nextTick(() => {
/> />
</li> </li>
<li> <li>
<span>隐藏标签页</span> <span class="dark:text-white">隐藏标签页</span>
<el-switch <el-switch
v-model="settings.tabsVal" v-model="settings.tabsVal"
inline-prompt inline-prompt
@@ -406,7 +344,7 @@ nextTick(() => {
/> />
</li> </li>
<li> <li>
<span>侧边栏Logo</span> <span class="dark:text-white">侧边栏Logo</span>
<el-switch <el-switch
v-model="logoVal" v-model="logoVal"
inline-prompt inline-prompt
@@ -419,7 +357,7 @@ nextTick(() => {
/> />
</li> </li>
<li> <li>
<span>标签页持久化</span> <span class="dark:text-white">标签页持久化</span>
<el-switch <el-switch
v-model="settings.multiTagsCache" v-model="settings.multiTagsCache"
inline-prompt inline-prompt
@@ -431,7 +369,7 @@ nextTick(() => {
</li> </li>
<li> <li>
<span>标签风格</span> <span class="dark:text-white">标签风格</span>
<el-radio-group v-model="markValue" size="small" @change="onChange"> <el-radio-group v-model="markValue" size="small" @change="onChange">
<el-radio label="card">卡片</el-radio> <el-radio label="card">卡片</el-radio>
<el-radio label="smart">灵动</el-radio> <el-radio label="smart">灵动</el-radio>
@@ -446,13 +384,13 @@ nextTick(() => {
@click="onReset" @click="onReset"
> >
<IconifyIconOffline <IconifyIconOffline
icon="logout-circle-r-line" icon="fa-sign-out"
width="15" width="15"
height="15" height="15"
style="margin-right: 4px" style="margin-right: 4px"
/> />
清空缓存并返回登录页</el-button 清空缓存并返回登录页
> </el-button>
</panel> </panel>
</template> </template>

View File

@@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, watch } from "vue";
import { isEqual } from "lodash-unified"; import { isEqual } from "lodash-unified";
import { transformI18n } from "/@/plugins/i18n"; import { transformI18n } from "/@/plugins/i18n";
import { ref, watch, onMounted, toRaw } from "vue";
import { getParentPaths, findRouteByPath } from "/@/router/utils"; import { getParentPaths, findRouteByPath } from "/@/router/utils";
import { useMultiTagsStoreHook } from "/@/store/modules/multiTags"; import { useMultiTagsStoreHook } from "/@/store/modules/multiTags";
import { useRoute, useRouter, RouteLocationMatched } from "vue-router"; import { useRoute, useRouter, RouteLocationMatched } from "vue-router";
@@ -9,24 +9,29 @@ import { useRoute, useRouter, RouteLocationMatched } from "vue-router";
const route = useRoute(); const route = useRoute();
const levelList = ref([]); const levelList = ref([]);
const router = useRouter(); const router = useRouter();
const routes = router.options.routes; const routes: any = router.options.routes;
const multiTags = useMultiTagsStoreHook().multiTags; const multiTags: any = useMultiTagsStoreHook().multiTags;
const isDashboard = (route: RouteLocationMatched): boolean | string => { const isDashboard = (route: RouteLocationMatched): boolean | string => {
const name = route && (route.name as string); const name = route && (route.name as string);
if (!name) { if (!name) return false;
return false; return name.trim().toLocaleLowerCase() === "Welcome".toLocaleLowerCase();
}
return name.trim().toLocaleLowerCase() === "welcome".toLocaleLowerCase();
}; };
const getBreadcrumb = (): void => { const getBreadcrumb = (): void => {
// 当前路由信息 // 当前路由信息
let currentRoute; let currentRoute;
if (Object.keys(route.query).length > 0) { if (Object.keys(route.query).length > 0) {
multiTags.forEach(item => { multiTags.forEach(item => {
if (isEqual(route.query, item?.query)) { if (isEqual(route.query, item?.query)) {
currentRoute = item; currentRoute = toRaw(item);
}
});
} else if (Object.keys(route.params).length > 0) {
multiTags.forEach(item => {
if (isEqual(route.params, item?.params)) {
currentRoute = toRaw(item);
} }
}); });
} else { } else {
@@ -38,29 +43,12 @@ const getBreadcrumb = (): void => {
let matched = []; let matched = [];
// 获取每个父级路径对应的路由信息 // 获取每个父级路径对应的路由信息
parentRoutes.forEach(path => { parentRoutes.forEach(path => {
if (path !== "/") { if (path !== "/") matched.push(findRouteByPath(path, routes));
matched.push(findRouteByPath(path, routes));
}
}); });
if (router.currentRoute.value.meta?.refreshRedirect) {
matched.unshift(
findRouteByPath(
router.currentRoute.value.meta.refreshRedirect as string,
routes
)
);
} else {
// 过滤与子级相同标题的父级路由
matched = matched.filter(item => {
return !item.redirect || (item.redirect && item.children.length !== 1);
});
}
if (currentRoute?.path !== "/welcome") {
matched.push(currentRoute);
}
const first = matched[0]; if (currentRoute?.path !== "/welcome") matched.push(currentRoute);
if (!isDashboard(first)) {
if (!isDashboard(matched[0])) {
matched = [ matched = [
{ {
path: "/welcome", path: "/welcome",
@@ -70,59 +58,51 @@ const getBreadcrumb = (): void => {
].concat(matched); ].concat(matched);
} }
matched.forEach((item, index) => {
if (currentRoute?.query || currentRoute?.params) return;
if (item?.children) {
item.children.forEach(v => {
if (v?.meta?.title === item?.meta?.title) {
matched.splice(index, 1);
}
});
}
});
levelList.value = matched.filter( levelList.value = matched.filter(
item => item?.meta && item?.meta.title !== false item => item?.meta && item?.meta.title !== false
); );
}; };
getBreadcrumb(); const handleLink = (item: RouteLocationMatched): void => {
const { redirect, path } = item;
if (redirect) {
router.push(redirect as any);
} else {
router.push(path);
}
};
onMounted(() => {
getBreadcrumb();
});
watch( watch(
() => route.path, () => route.path,
() => getBreadcrumb() () => {
); getBreadcrumb();
watch(
() => route.query,
() => getBreadcrumb()
);
const handleLink = (item: RouteLocationMatched): any => {
const { redirect, path } = item;
if (redirect) {
router.push(redirect.toString());
return;
} }
router.push(path); );
};
</script> </script>
<template> <template>
<el-breadcrumb class="app-breadcrumb" separator="/"> <el-breadcrumb class="!leading-[50px] select-none" separator="/">
<transition-group appear name="breadcrumb"> <transition-group appear name="breadcrumb">
<el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path"> <el-breadcrumb-item v-for="item in levelList" :key="item.path">
<span <a @click.prevent="handleLink(item)">
v-if="item.redirect === 'noRedirect' || index == levelList.length - 1"
class="no-redirect"
>{{ transformI18n(item.meta.title) }}</span
>
<a v-else @click.prevent="handleLink(item)">
{{ transformI18n(item.meta.title) }} {{ transformI18n(item.meta.title) }}
</a> </a>
</el-breadcrumb-item> </el-breadcrumb-item>
</transition-group> </transition-group>
</el-breadcrumb> </el-breadcrumb>
</template> </template>
<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
display: inline-block;
font-size: 14px;
line-height: 50px;
.no-redirect {
color: #97a8be;
cursor: text;
}
}
</style>

View File

@@ -1,63 +0,0 @@
<script setup lang="ts">
import { ref } from "vue";
import { useEpThemeStoreHook } from "/@/store/modules/epTheme";
export interface Props {
isActive: boolean;
}
const props = withDefaults(defineProps<Props>(), {
isActive: false
});
const fillColor = ref<string>("");
const emit = defineEmits<{
(e: "toggleClick"): void;
}>();
const toggleClick = () => {
emit("toggleClick");
};
</script>
<template>
<div
:class="classes.container"
:title="props.isActive ? '点击折叠' : '点击展开'"
@click="toggleClick"
@mouseenter="fillColor = useEpThemeStoreHook().epThemeColor"
@mouseleave="fillColor = ''"
>
<svg
:fill="fillColor"
:class="['hamburger', props.isActive ? 'is-active' : '']"
viewBox="0 0 1024 1024"
xmlns="http://www.w3.org/2000/svg"
width="64"
height="64"
>
<path
d="M408 442h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8zm-8 204c0 4.4 3.6 8 8 8h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56zm504-486H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 632H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM142.4 642.1L298.7 519a8.84 8.84 0 0 0 0-13.9L142.4 381.9c-5.8-4.6-14.4-.5-14.4 6.9v246.3a8.9 8.9 0 0 0 14.4 7z"
/>
</svg>
</div>
</template>
<style module="classes" scoped>
.container {
padding: 0 15px;
}
</style>
<style scoped>
.hamburger {
display: inline-block;
vertical-align: middle;
width: 20px;
height: 20px;
}
.is-active {
transform: rotate(180deg);
}
</style>

View File

@@ -1,70 +1,41 @@
<script setup lang="ts"> <script setup lang="ts">
import { useI18n } from "vue-i18n";
import { useNav } from "../../hooks/nav";
import Search from "../search/index.vue"; import Search from "../search/index.vue";
import Notice from "../notice/index.vue"; import Notice from "../notice/index.vue";
import { templateRef } from "@vueuse/core"; import { ref, watch, nextTick } from "vue";
import SidebarItem from "./sidebarItem.vue"; import SidebarItem from "./sidebarItem.vue";
import avatars from "/@/assets/avatars.jpg"; import avatars from "/@/assets/avatars.jpg";
import screenfull from "../screenfull/index.vue"; import { useNav } from "/@/layout/hooks/useNav";
import { useRoute, useRouter } from "vue-router"; import { useTranslationLang } from "../../hooks/useTranslationLang";
import { deviceDetection } from "/@/utils/deviceDetection";
import { watch, nextTick, onMounted, getCurrentInstance } from "vue";
import { usePermissionStoreHook } from "/@/store/modules/permission"; import { usePermissionStoreHook } from "/@/store/modules/permission";
import globalization from "/@/assets/svg/globalization.svg?component"; import globalization from "/@/assets/svg/globalization.svg?component";
const route = useRoute(); const menuRef = ref();
const { locale, t } = useI18n();
const routers = useRouter().options.routes;
const menuRef = templateRef<ElRef | null>("menu", null);
const instance =
getCurrentInstance().appContext.config.globalProperties.$storage;
const title =
getCurrentInstance().appContext.config.globalProperties.$config?.Title;
const { t, route, locale, translationCh, translationEn } =
useTranslationLang(menuRef);
const { const {
title,
routers,
logout, logout,
backHome, backHome,
onPanel, onPanel,
changeTitle,
handleResize,
menuSelect, menuSelect,
username, username,
avatarsStyle, avatarsStyle,
getDropdownItemStyle getDropdownItemStyle,
getDropdownItemClass
} = useNav(); } = useNav();
onMounted(() => { nextTick(() => {
nextTick(() => { menuRef.value?.handleResize();
handleResize(menuRef.value);
});
}); });
watch(
() => locale.value,
() => {
changeTitle(route.meta);
}
);
watch( watch(
() => route.path, () => route.path,
() => { () => {
menuSelect(route.path, routers); menuSelect(route.path, routers);
} }
); );
function translationCh() {
instance.locale = { locale: "zh" };
locale.value = "zh";
handleResize(menuRef.value);
}
function translationEn() {
instance.locale = { locale: "en" };
locale.value = "en";
handleResize(menuRef.value);
}
</script> </script>
<template> <template>
@@ -74,11 +45,11 @@ function translationEn() {
<h4>{{ title }}</h4> <h4>{{ title }}</h4>
</div> </div>
<el-menu <el-menu
ref="menu"
class="horizontal-header-menu"
mode="horizontal"
:default-active="route.path"
router router
ref="menuRef"
mode="horizontal"
class="horizontal-header-menu"
:default-active="route.path"
@select="indexPath => menuSelect(indexPath, routers)" @select="indexPath => menuSelect(indexPath, routers)"
> >
<sidebar-item <sidebar-item
@@ -93,37 +64,41 @@ function translationEn() {
<Search /> <Search />
<!-- 通知 --> <!-- 通知 -->
<Notice id="header-notice" /> <Notice id="header-notice" />
<!-- 全屏 -->
<screenfull id="header-screenfull" v-show="!deviceDetection()" />
<!-- 国际化 --> <!-- 国际化 -->
<el-dropdown id="header-translation" trigger="click"> <el-dropdown id="header-translation" trigger="click">
<globalization /> <globalization
class="navbar-bg-hover w-[40px] h-[48px] p-[11px] cursor-pointer outline-none"
/>
<template #dropdown> <template #dropdown>
<el-dropdown-menu class="translation"> <el-dropdown-menu class="translation">
<el-dropdown-item <el-dropdown-item
:style="getDropdownItemStyle(locale, 'zh')" :style="getDropdownItemStyle(locale, 'zh')"
:class="['dark:!text-white', getDropdownItemClass(locale, 'zh')]"
@click="translationCh" @click="translationCh"
> >
<span class="check-zh" v-show="locale === 'zh'"> <span class="check-zh" v-show="locale === 'zh'">
<IconifyIconOffline icon="check" /> </span <IconifyIconOffline icon="check" />
>简体中文 </span>
简体中文
</el-dropdown-item> </el-dropdown-item>
<el-dropdown-item <el-dropdown-item
:style="getDropdownItemStyle(locale, 'en')" :style="getDropdownItemStyle(locale, 'en')"
:class="['dark:!text-white', getDropdownItemClass(locale, 'en')]"
@click="translationEn" @click="translationEn"
> >
<span class="check-en" v-show="locale === 'en'"> <span class="check-en" v-show="locale === 'en'">
<IconifyIconOffline icon="check" /> </span <IconifyIconOffline icon="check" />
>English</el-dropdown-item </span>
> English
</el-dropdown-item>
</el-dropdown-menu> </el-dropdown-menu>
</template> </template>
</el-dropdown> </el-dropdown>
<!-- 退出登 --> <!-- 退出登 -->
<el-dropdown trigger="click"> <el-dropdown trigger="click">
<span class="el-dropdown-link"> <span class="el-dropdown-link navbar-bg-hover">
<img v-if="avatars" :src="avatars" :style="avatarsStyle" /> <img v-if="avatars" :src="avatars" :style="avatarsStyle" />
<p v-if="username">{{ username }}</p> <p v-if="username" class="dark:text-white">{{ username }}</p>
</span> </span>
<template #dropdown> <template #dropdown>
<el-dropdown-menu class="logout"> <el-dropdown-menu class="logout">
@@ -132,13 +107,13 @@ function translationEn() {
icon="logout-circle-r-line" icon="logout-circle-r-line"
style="margin: 5px" style="margin: 5px"
/> />
{{ t("buttons.hsLoginOut") }}</el-dropdown-item {{ t("buttons.hsLoginOut") }}
> </el-dropdown-item>
</el-dropdown-menu> </el-dropdown-menu>
</template> </template>
</el-dropdown> </el-dropdown>
<span <span
class="el-icon-setting" class="set-icon navbar-bg-hover"
:title="t('buttons.hssystemSet')" :title="t('buttons.hssystemSet')"
@click="onPanel" @click="onPanel"
> >

View File

@@ -0,0 +1,47 @@
<script setup lang="ts">
import { useDark } from "@pureadmin/utils";
interface Props {
isActive: boolean;
}
const props = withDefaults(defineProps<Props>(), {
isActive: false
});
const { isDark } = useDark();
const emit = defineEmits<{
(e: "toggleClick"): void;
}>();
const toggleClick = () => {
emit("toggleClick");
};
</script>
<template>
<div class="container">
<el-tooltip
placement="right"
:effect="isDark ? 'dark' : 'light'"
:content="props.isActive ? '点击折叠' : '点击展开'"
>
<IconifyIconOffline
:icon="props.isActive ? 'menu-fold' : 'menu-unfold'"
class="cursor-pointer inline-block align-middle text-primary hover:text-primary dark:hover:!text-white w-[16px] h-[16px] ml-4 mb-1"
@click="toggleClick"
/>
</el-tooltip>
</div>
</template>
<style lang="scss" scoped>
.container {
position: absolute;
bottom: 0;
width: 100%;
height: 40px;
line-height: 40px;
box-shadow: 0 0 6px -2px var(--el-color-primary);
}
</style>

View File

@@ -1,11 +1,11 @@
<script setup lang="ts"> <script setup lang="ts">
import { getCurrentInstance } from "vue"; import { useNav } from "/@/layout/hooks/useNav";
const props = defineProps({ const props = defineProps({
collapse: Boolean collapse: Boolean
}); });
const title = const { title } = useNav();
getCurrentInstance().appContext.config.globalProperties.$config?.Title;
</script> </script>
<template> <template>
@@ -51,6 +51,12 @@ const title =
margin-top: 5px; margin-top: 5px;
.sidebar-title { .sidebar-title {
display: block;
width: 160px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-align: left;
color: #1890ff; color: #1890ff;
font-weight: 600; font-weight: 600;
font-size: 20px; font-size: 20px;

View File

@@ -1,47 +1,37 @@
<script setup lang="ts"> <script setup lang="ts">
import { useI18n } from "vue-i18n";
import Search from "../search/index.vue"; import Search from "../search/index.vue";
import Notice from "../notice/index.vue"; import Notice from "../notice/index.vue";
import { useNav } from "../../hooks/nav";
import { templateRef } from "@vueuse/core";
import avatars from "/@/assets/avatars.jpg"; import avatars from "/@/assets/avatars.jpg";
import { useNav } from "/@/layout/hooks/useNav";
import { transformI18n } from "/@/plugins/i18n"; import { transformI18n } from "/@/plugins/i18n";
import screenfull from "../screenfull/index.vue"; import { ref, toRaw, watch, onMounted, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { deviceDetection } from "/@/utils/deviceDetection";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks"; import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { useEpThemeStoreHook } from "/@/store/modules/epTheme";
import { getParentPaths, findRouteByPath } from "/@/router/utils"; import { getParentPaths, findRouteByPath } from "/@/router/utils";
import { useTranslationLang } from "../../hooks/useTranslationLang";
import { usePermissionStoreHook } from "/@/store/modules/permission"; import { usePermissionStoreHook } from "/@/store/modules/permission";
import globalization from "/@/assets/svg/globalization.svg?component"; import globalization from "/@/assets/svg/globalization.svg?component";
import { ref, watch, nextTick, onMounted, getCurrentInstance } from "vue";
const route = useRoute(); const menuRef = ref();
const { locale, t } = useI18n(); let defaultActive = ref(null);
const routers = useRouter().options.routes;
const menuRef = templateRef<ElRef | null>("menu", null);
const instance =
getCurrentInstance().appContext.config.globalProperties.$storage;
const { t, route, locale, translationCh, translationEn } =
useTranslationLang(menuRef);
const { const {
device,
routers,
logout, logout,
onPanel, onPanel,
changeTitle,
toggleSideBar,
handleResize,
menuSelect, menuSelect,
resolvePath, resolvePath,
pureApp,
username, username,
avatarsStyle, avatarsStyle,
getDropdownItemStyle getDropdownItemStyle,
getDropdownItemClass
} = useNav(); } = useNav();
let defaultActive = ref(null);
function getDefaultActive(routePath) { function getDefaultActive(routePath) {
const wholeMenus = usePermissionStoreHook().wholeMenus; const wholeMenus = usePermissionStoreHook().wholeMenus;
// 当前路由的父级路径 /** 当前路由的父级路径 */
const parentRoutes = getParentPaths(routePath, wholeMenus)[0]; const parentRoutes = getParentPaths(routePath, wholeMenus)[0];
defaultActive.value = findRouteByPath( defaultActive.value = findRouteByPath(
parentRoutes, parentRoutes,
@@ -51,67 +41,28 @@ function getDefaultActive(routePath) {
onMounted(() => { onMounted(() => {
getDefaultActive(route.path); getDefaultActive(route.path);
nextTick(() => { });
handleResize(menuRef.value);
}); nextTick(() => {
menuRef.value?.handleResize();
}); });
watch( watch(
() => locale.value, () => [route.path, usePermissionStoreHook().wholeMenus],
() => {
changeTitle(route.meta);
}
);
watch(
() => route.path,
() => { () => {
getDefaultActive(route.path); getDefaultActive(route.path);
} }
); );
function translationCh() {
instance.locale = { locale: "zh" };
locale.value = "zh";
handleResize(menuRef.value);
}
function translationEn() {
instance.locale = { locale: "en" };
locale.value = "en";
handleResize(menuRef.value);
}
</script> </script>
<template> <template>
<div class="horizontal-header"> <div v-if="device !== 'mobile'" class="horizontal-header">
<div
:class="classes.container"
:title="pureApp.sidebar.opened ? '点击折叠' : '点击展开'"
@click="toggleSideBar"
>
<svg
:fill="useEpThemeStoreHook().fill"
:class="[
'hamburger',
pureApp.sidebar.opened ? 'is-active-hamburger' : ''
]"
viewBox="0 0 1024 1024"
xmlns="http://www.w3.org/2000/svg"
width="64"
height="64"
>
<path
d="M408 442h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8zm-8 204c0 4.4 3.6 8 8 8h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56zm504-486H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 632H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM142.4 642.1L298.7 519a8.84 8.84 0 0 0 0-13.9L142.4 381.9c-5.8-4.6-14.4-.5-14.4 6.9v246.3a8.9 8.9 0 0 0 14.4 7z"
/>
</svg>
</div>
<el-menu <el-menu
ref="menu"
class="horizontal-header-menu"
mode="horizontal"
:default-active="defaultActive"
router router
ref="menuRef"
mode="horizontal"
class="horizontal-header-menu"
:default-active="defaultActive"
@select="indexPath => menuSelect(indexPath, routers)" @select="indexPath => menuSelect(indexPath, routers)"
> >
<el-menu-item <el-menu-item
@@ -120,10 +71,15 @@ function translationEn() {
:index="resolvePath(route) || route.redirect" :index="resolvePath(route) || route.redirect"
> >
<template #title> <template #title>
<div v-show="route.meta.icon" :class="['el-icon', route.meta.icon]"> <div
<component :is="useRenderIcon(route.meta && route.meta.icon)" /> v-if="toRaw(route.meta.icon)"
:class="['sub-menu-icon', route.meta.icon]"
>
<component
:is="useRenderIcon(route.meta && toRaw(route.meta.icon))"
/>
</div> </div>
<span>{{ transformI18n(route.meta.title) }}</span> <span class="select-none">{{ transformI18n(route.meta.title) }}</span>
<FontIcon <FontIcon
v-if="route.meta.extraIcon" v-if="route.meta.extraIcon"
width="30px" width="30px"
@@ -140,35 +96,41 @@ function translationEn() {
<Search /> <Search />
<!-- 通知 --> <!-- 通知 -->
<Notice id="header-notice" /> <Notice id="header-notice" />
<!-- 全屏 -->
<screenfull id="header-screenfull" v-show="!deviceDetection()" />
<!-- 国际化 --> <!-- 国际化 -->
<el-dropdown id="header-translation" trigger="click"> <el-dropdown id="header-translation" trigger="click">
<globalization /> <globalization
class="navbar-bg-hover w-[40px] h-[48px] p-[11px] cursor-pointer outline-none"
/>
<template #dropdown> <template #dropdown>
<el-dropdown-menu class="translation"> <el-dropdown-menu class="translation">
<el-dropdown-item <el-dropdown-item
:style="getDropdownItemStyle(locale, 'zh')" :style="getDropdownItemStyle(locale, 'zh')"
:class="['dark:!text-white', getDropdownItemClass(locale, 'zh')]"
@click="translationCh" @click="translationCh"
><span class="check-zh" v-show="locale === 'zh'"
><IconifyIconOffline icon="check" /></span
>简体中文</el-dropdown-item
> >
<span class="check-zh" v-show="locale === 'zh'">
<IconifyIconOffline icon="check" />
</span>
简体中文
</el-dropdown-item>
<el-dropdown-item <el-dropdown-item
:style="getDropdownItemStyle(locale, 'en')" :style="getDropdownItemStyle(locale, 'en')"
:class="['dark:!text-white', getDropdownItemClass(locale, 'en')]"
@click="translationEn" @click="translationEn"
><span class="check-en" v-show="locale === 'en'"
><IconifyIconOffline icon="check" /></span
>English</el-dropdown-item
> >
<span class="check-en" v-show="locale === 'en'">
<IconifyIconOffline icon="check" />
</span>
English
</el-dropdown-item>
</el-dropdown-menu> </el-dropdown-menu>
</template> </template>
</el-dropdown> </el-dropdown>
<!-- 退出登 --> <!-- 退出登 -->
<el-dropdown trigger="click"> <el-dropdown trigger="click">
<span class="el-dropdown-link"> <span class="el-dropdown-link navbar-bg-hover">
<img v-if="avatars" :src="avatars" :style="avatarsStyle" /> <img v-if="avatars" :src="avatars" :style="avatarsStyle" />
<p v-if="username">{{ username }}</p> <p v-if="username" class="dark:text-white">{{ username }}</p>
</span> </span>
<template #dropdown> <template #dropdown>
<el-dropdown-menu class="logout"> <el-dropdown-menu class="logout">
@@ -177,13 +139,13 @@ function translationEn() {
icon="logout-circle-r-line" icon="logout-circle-r-line"
style="margin: 5px" style="margin: 5px"
/> />
{{ t("buttons.hsLoginOut") }}</el-dropdown-item {{ t("buttons.hsLoginOut") }}
> </el-dropdown-item>
</el-dropdown-menu> </el-dropdown-menu>
</template> </template>
</el-dropdown> </el-dropdown>
<span <span
class="el-icon-setting" class="set-icon navbar-bg-hover"
:title="t('buttons.hssystemSet')" :title="t('buttons.hssystemSet')"
@click="onPanel" @click="onPanel"
> >
@@ -193,26 +155,7 @@ function translationEn() {
</div> </div>
</template> </template>
<style module="classes" scoped>
.container {
padding: 0 15px;
}
</style>
<style lang="scss" scoped> <style lang="scss" scoped>
.hamburger {
width: 20px;
height: 20px;
&:hover {
cursor: pointer;
}
}
.is-active-hamburger {
transform: rotate(180deg);
}
.translation { .translation {
::v-deep(.el-dropdown-menu__item) { ::v-deep(.el-dropdown-menu__item) {
padding: 5px 40px; padding: 5px 40px;

View File

@@ -1,14 +1,12 @@
<script setup lang="ts"> <script setup lang="ts">
import path from "path"; import path from "path";
import { useNav } from "../../hooks/nav";
import { childrenType } from "../../types"; import { childrenType } from "../../types";
import { useNav } from "/@/layout/hooks/useNav";
import { transformI18n } from "/@/plugins/i18n"; import { transformI18n } from "/@/plugins/i18n";
import { useAppStoreHook } from "/@/store/modules/app";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks"; import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { ref, PropType, nextTick, computed, CSSProperties } from "vue"; import { ref, toRaw, PropType, nextTick, computed, CSSProperties } from "vue";
const { pureApp } = useNav(); const { layout, isCollapse } = useNav();
const menuMode = ["vertical", "mix"].includes(pureApp.layout);
const props = defineProps({ const props = defineProps({
item: { item: {
@@ -25,7 +23,7 @@ const props = defineProps({
}); });
const getExtraIconStyle = computed((): CSSProperties => { const getExtraIconStyle = computed((): CSSProperties => {
if (useAppStoreHook().getSidebarStatus) { if (!isCollapse.value) {
return { return {
position: "absolute", position: "absolute",
right: "10px" right: "10px"
@@ -46,7 +44,7 @@ const getNoDropdownStyle = computed((): CSSProperties => {
const getDivStyle = computed((): CSSProperties => { const getDivStyle = computed((): CSSProperties => {
return { return {
width: pureApp.sidebar.opened ? "" : "100%", width: !isCollapse.value ? "" : "100%",
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
justifyContent: "space-between", justifyContent: "space-between",
@@ -54,9 +52,8 @@ const getDivStyle = computed((): CSSProperties => {
}; };
}); });
const getMenuTextStyle = computed((): CSSProperties => { const getMenuTextStyle = computed(() => {
return { return {
width: pureApp.sidebar.opened ? "125px" : "",
overflow: "hidden", overflow: "hidden",
textOverflow: "ellipsis", textOverflow: "ellipsis",
outline: "none" outline: "none"
@@ -65,14 +62,14 @@ const getMenuTextStyle = computed((): CSSProperties => {
const getSubTextStyle = computed((): CSSProperties => { const getSubTextStyle = computed((): CSSProperties => {
return { return {
width: pureApp.sidebar.opened ? "125px" : "", width: !isCollapse.value ? "210px" : "",
display: "inline-block", display: "inline-block",
overflow: "hidden", overflow: "hidden",
textOverflow: "ellipsis" textOverflow: "ellipsis"
}; };
}); });
const getSpanStyle = computed((): CSSProperties => { const getSpanStyle = computed(() => {
return { return {
overflow: "hidden", overflow: "hidden",
textOverflow: "ellipsis" textOverflow: "ellipsis"
@@ -148,21 +145,31 @@ function resolvePath(routePath) {
:class="{ 'submenu-title-noDropdown': !isNest }" :class="{ 'submenu-title-noDropdown': !isNest }"
:style="getNoDropdownStyle" :style="getNoDropdownStyle"
> >
<div class="sub-menu-icon" v-show="props.item.meta.icon"> <div class="sub-menu-icon" v-if="toRaw(props.item.meta.icon)">
<component <component
:is=" :is="
useRenderIcon( useRenderIcon(
onlyOneChild.meta.icon || toRaw(onlyOneChild.meta.icon) ||
(props.item.meta && props.item.meta.icon) (props.item.meta && toRaw(props.item.meta.icon))
) )
" "
/> />
</div> </div>
<div <div
v-if=" v-if="
!pureApp.sidebar.opened && isCollapse &&
pureApp.layout === 'mix' && layout === 'vertical' &&
props.item?.pathList?.length === 2 props.item?.pathList?.length === 1
"
:style="getDivStyle"
>
<span :style="getMenuTextStyle">
{{ transformI18n(onlyOneChild.meta.title) }}
</span>
</div>
<div
v-if="
isCollapse && layout === 'mix' && props.item?.pathList?.length === 2
" "
:style="getDivStyle" :style="getDivStyle"
> >
@@ -172,9 +179,9 @@ function resolvePath(routePath) {
</div> </div>
<template #title> <template #title>
<div :style="getDivStyle"> <div :style="getDivStyle">
<span v-if="!menuMode">{{ <span v-if="layout === 'horizontal'">
transformI18n(onlyOneChild.meta.title) {{ transformI18n(onlyOneChild.meta.title) }}
}}</span> </span>
<el-tooltip <el-tooltip
v-else v-else
placement="top" placement="top"
@@ -205,24 +212,21 @@ function resolvePath(routePath) {
</el-menu-item> </el-menu-item>
</template> </template>
<el-sub-menu <el-sub-menu v-else ref="subMenu" :index="resolvePath(props.item.path)">
v-else
ref="subMenu"
:index="resolvePath(props.item.path)"
popper-append-to-body
>
<template #title> <template #title>
<div v-show="props.item.meta.icon" class="sub-menu-icon"> <div v-if="toRaw(props.item.meta.icon)" class="sub-menu-icon">
<component <component
:is="useRenderIcon(props.item.meta && props.item.meta.icon)" :is="useRenderIcon(props.item.meta && toRaw(props.item.meta.icon))"
/> />
</div> </div>
<span v-if="!menuMode">{{ transformI18n(props.item.meta.title) }}</span> <span v-if="layout === 'horizontal'">
{{ transformI18n(props.item.meta.title) }}
</span>
<el-tooltip <el-tooltip
v-else v-else
placement="top" placement="top"
:offset="-10" :offset="-10"
:disabled="!pureApp.sidebar.opened || !props.item.showTooltip" :disabled="!isCollapse || !props.item.showTooltip"
> >
<template #content> <template #content>
{{ transformI18n(props.item.meta.title) }} {{ transformI18n(props.item.meta.title) }}

View File

@@ -0,0 +1,30 @@
<script setup lang="ts">
interface Props {
isActive: boolean;
}
const props = withDefaults(defineProps<Props>(), {
isActive: false
});
const emit = defineEmits<{
(e: "toggleClick"): void;
}>();
const toggleClick = () => {
emit("toggleClick");
};
</script>
<template>
<div
class="px-3 mr-1 navbar-bg-hover"
:title="props.isActive ? '点击折叠' : '点击展开'"
@click="toggleClick"
>
<IconifyIconOffline
:icon="props.isActive ? 'menu-fold' : 'menu-unfold'"
class="inline-block align-middle hover:text-primary dark:hover:!text-white"
/>
</div>
</template>

View File

@@ -1,31 +1,33 @@
<script setup lang="ts"> <script setup lang="ts">
import Logo from "./logo.vue"; import Logo from "./logo.vue";
import { useRoute } from "vue-router";
import { emitter } from "/@/utils/mitt"; import { emitter } from "/@/utils/mitt";
import { useNav } from "../../hooks/nav";
import SidebarItem from "./sidebarItem.vue"; import SidebarItem from "./sidebarItem.vue";
import { storageLocal } from "/@/utils/storage"; import leftCollapse from "./leftCollapse.vue";
import { useRoute, useRouter } from "vue-router"; import type { StorageConfigs } from "/#/index";
import { useNav } from "/@/layout/hooks/useNav";
import { storageLocal } from "@pureadmin/utils";
import { ref, computed, watch, onBeforeMount } from "vue"; import { ref, computed, watch, onBeforeMount } from "vue";
import { findRouteByPath, getParentPaths } from "/@/router/utils"; import { findRouteByPath, getParentPaths } from "/@/router/utils";
import { usePermissionStoreHook } from "/@/store/modules/permission"; import { usePermissionStoreHook } from "/@/store/modules/permission";
const route = useRoute(); const route = useRoute();
const routers = useRouter().options.routes;
const showLogo = ref( const showLogo = ref(
storageLocal.getItem("responsive-configure")?.showLogo ?? true storageLocal.getItem<StorageConfigs>("responsive-configure")?.showLogo ?? true
); );
const { pureApp, isCollapse, menuSelect } = useNav(); const { routers, device, pureApp, isCollapse, menuSelect, toggleSideBar } =
useNav();
let subMenuData = ref([]); let subMenuData = ref([]);
const menuData = computed(() => { const menuData = computed(() => {
return pureApp.layout === "mix" return pureApp.layout === "mix" && device.value !== "mobile"
? subMenuData.value ? subMenuData.value
: usePermissionStoreHook().wholeMenus; : usePermissionStoreHook().wholeMenus;
}); });
function getSubMenuData(path) { function getSubMenuData(path: string) {
// path的上级路由组成的数组 // path的上级路由组成的数组
const parentPathArr = getParentPaths( const parentPathArr = getParentPaths(
path, path,
@@ -39,6 +41,7 @@ function getSubMenuData(path) {
if (!parenetRoute?.children) return; if (!parenetRoute?.children) return;
subMenuData.value = parenetRoute?.children; subMenuData.value = parenetRoute?.children;
} }
getSubMenuData(route.path); getSubMenuData(route.path);
onBeforeMount(() => { onBeforeMount(() => {
@@ -48,7 +51,7 @@ onBeforeMount(() => {
}); });
watch( watch(
() => route.path, () => [route.path, usePermissionStoreHook().wholeMenus],
() => { () => {
getSubMenuData(route.path); getSubMenuData(route.path);
menuSelect(route.path, routers); menuSelect(route.path, routers);
@@ -59,25 +62,33 @@ watch(
<template> <template>
<div :class="['sidebar-container', showLogo ? 'has-logo' : '']"> <div :class="['sidebar-container', showLogo ? 'has-logo' : '']">
<Logo v-if="showLogo" :collapse="isCollapse" /> <Logo v-if="showLogo" :collapse="isCollapse" />
<el-scrollbar wrap-class="scrollbar-wrapper"> <el-scrollbar
wrap-class="scrollbar-wrapper"
:class="[device === 'mobile' ? 'mobile' : 'pc']"
>
<el-menu <el-menu
:default-active="route.path"
:collapse="isCollapse"
unique-opened
router router
:collapse-transition="false" unique-opened
mode="vertical" mode="vertical"
class="outer-most" class="outer-most select-none"
:collapse="isCollapse"
:default-active="route.path"
:collapse-transition="false"
@select="indexPath => menuSelect(indexPath, routers)" @select="indexPath => menuSelect(indexPath, routers)"
> >
<sidebar-item <sidebar-item
v-for="routes in menuData" v-for="routes in menuData"
:key="routes.path" :key="routes.path"
:item="routes" :item="routes"
class="outer-most"
:base-path="routes.path" :base-path="routes.path"
class="outer-most select-none"
/> />
</el-menu> </el-menu>
</el-scrollbar> </el-scrollbar>
<leftCollapse
v-if="device !== 'mobile'"
:is-active="pureApp.sidebar.opened"
@toggleClick="toggleSideBar"
/>
</div> </div>
</template> </template>

View File

@@ -43,7 +43,7 @@
font-size: 14px; font-size: 14px;
display: flex; display: flex;
align-items: center; align-items: center;
color: var(--el-text-color-regular); color: var(--el-text-color-primary);
background: #fff; background: #fff;
position: relative; position: relative;
box-shadow: 0 0 1px #888; box-shadow: 0 0 1px #888;
@@ -92,7 +92,7 @@
a { a {
text-decoration: none; text-decoration: none;
color: #666; color: var(--el-text-color-primary);
padding: 0 4px; padding: 0 4px;
} }
@@ -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 { .contextmenu {
margin: 0; margin: 0;
@@ -144,7 +129,7 @@
list-style-type: none; list-style-type: none;
padding: 5px 0; padding: 5px 0;
border-radius: 4px; border-radius: 4px;
color: #000000d9; color: var(--el-text-color-primary);
font-weight: normal; font-weight: normal;
font-size: 13px; font-size: 13px;
white-space: nowrap; white-space: nowrap;
@@ -160,7 +145,7 @@
align-items: center; align-items: center;
&:hover { &:hover {
background: var(--el-color-primary-light-9); // background: var(--el-color-primary-light-9);
color: var(--el-color-primary); color: var(--el-color-primary);
} }
@@ -173,8 +158,6 @@
} }
.el-dropdown-menu { .el-dropdown-menu {
padding: 0;
li { li {
width: 100%; width: 100%;
margin: 0; margin: 0;
@@ -198,6 +181,9 @@
margin-right: 10px; margin-right: 10px;
} }
:deep(.el-dropdown-menu__item--divided) {
margin: 1px 0;
}
.el-dropdown-menu__item--divided::before { .el-dropdown-menu__item--divided::before {
margin: 0; margin: 0;
} }
@@ -207,7 +193,7 @@
} }
.scroll-item.is-active { .scroll-item.is-active {
background-color: var(--el-color-primary-light-9); // background-color: var(--el-color-primary-light-9);
position: relative; position: relative;
color: #fff; color: #fff;
@@ -220,15 +206,16 @@
} }
a { a {
color: var(--el-color-primary); color: var(--el-color-primary) !important;
} }
} }
.arrow-left, .arrow-left,
.arrow-right { .arrow-right,
.arrow-down {
width: 40px; width: 40px;
height: 38px; height: 38px;
color: #00000073; color: var(--el-text-color-primary);
position: relative; position: relative;
svg { svg {
@@ -250,7 +237,7 @@
.arrow-right { .arrow-right {
box-shadow: -5px 0 5px -6px #ccc; box-shadow: -5px 0 5px -6px #ccc;
border-right: 1px solid #ccc; border-right: 0.5px solid #ccc;
&:hover { &:hover {
cursor: e-resize; cursor: e-resize;
@@ -307,8 +294,3 @@
background: var(--el-color-primary); background: var(--el-color-primary);
animation: scheduleOutWidth 400ms ease-in; animation: scheduleOutWidth 400ms ease-in;
} }
/* 刷新按钮动画效果 */
.refresh-button {
animation: rotate 600ms linear infinite;
}

View File

@@ -1,115 +1,56 @@
<script setup lang="ts"> <script setup lang="ts">
import { import { $t } from "/@/plugins/i18n";
ref,
watch,
unref,
toRaw,
reactive,
nextTick,
computed,
ComputedRef,
CSSProperties,
onBeforeMount,
getCurrentInstance
} from "vue";
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";
import { useI18n } from "vue-i18n";
import { emitter } from "/@/utils/mitt"; import { emitter } from "/@/utils/mitt";
import { storageLocal } from "/@/utils/storage"; import { RouteConfigs } from "../../types";
import { useRoute, useRouter } from "vue-router"; import { useTags } from "../../hooks/useTag";
import { routerArrays } from "/@/layout/types";
import { isEqual, isEmpty } from "lodash-unified"; import { isEqual, isEmpty } from "lodash-unified";
import { transformI18n, $t } from "/@/plugins/i18n";
import { RouteConfigs, tagsViewsType } from "../../types";
import { useSettingStoreHook } from "/@/store/modules/settings"; import { useSettingStoreHook } from "/@/store/modules/settings";
import { ref, watch, unref, nextTick, onBeforeMount } from "vue";
import { handleAliveRoute, delAliveRoutes } from "/@/router/utils"; import { handleAliveRoute, delAliveRoutes } from "/@/router/utils";
import { useMultiTagsStoreHook } from "/@/store/modules/multiTags"; import { useMultiTagsStoreHook } from "/@/store/modules/multiTags";
import { usePermissionStoreHook } from "/@/store/modules/permission"; import { useResizeObserver, useDebounceFn, useFullscreen } from "@vueuse/core";
import { toggleClass, removeClass, hasClass } from "/@/utils/operate";
import { templateRef, useResizeObserver, useDebounceFn } from "@vueuse/core";
const { t } = useI18n(); const {
const route = useRoute(); route,
const router = useRouter(); router,
const translateX = ref<number>(0); visible,
const activeIndex = ref<number>(-1); showTags,
let refreshButton = "refresh-button"; instance,
const instance = getCurrentInstance(); multiTags,
const pureSetting = useSettingStoreHook(); tagsViews,
const tabDom = templateRef<HTMLElement | null>("tabDom", null); buttonTop,
const containerDom = templateRef<HTMLElement | null>("containerDom", null); buttonLeft,
const scrollbarDom = templateRef<HTMLElement | null>("scrollbarDom", null); showModel,
const showTags = translateX,
ref(storageLocal.getItem("responsive-configure").hideTabs) ?? "false"; pureSetting,
let multiTags: ComputedRef<Array<RouteConfigs>> = computed(() => { activeIndex,
return useMultiTagsStoreHook()?.multiTags; getTabStyle,
}); iconIsActive,
linkIsActive,
currentSelect,
scheduleIsActive,
getContextMenuStyle,
closeMenu,
onMounted,
onMouseenter,
onMouseleave,
transformI18n,
onContentFullScreen
} = useTags();
const linkIsActive = computed(() => { const tabDom = ref();
return item => { const containerDom = ref();
if (Object.keys(route.query).length === 0) { const scrollbarDom = ref();
if (route.path === item.path) { let isShowArrow = ref(false);
return "is-active"; const { isFullscreen, toggle } = useFullscreen();
} else {
return "";
}
} else {
if (isEqual(route?.query, item?.query)) {
return "is-active";
} else {
return "";
}
}
};
});
const scheduleIsActive = computed(() => {
return item => {
if (Object.keys(route.query).length === 0) {
if (route.path === item.path) {
return "schedule-active";
} else {
return "";
}
} else {
if (isEqual(route?.query, item?.query)) {
return "schedule-active";
} else {
return "";
}
}
};
});
const iconIsActive = computed(() => {
return (item, index) => {
if (index === 0) return;
if (Object.keys(route.query).length === 0) {
if (route.path === item.path) {
return true;
} else {
return false;
}
} else {
if (isEqual(route?.query, item?.query)) {
return true;
} else {
return false;
}
}
};
});
const dynamicTagView = () => { const dynamicTagView = () => {
const index = multiTags.value.findIndex(item => { const index = multiTags.value.findIndex(item => {
if (item?.query) { if (item.query) {
return isEqual(route?.query, item?.query); return isEqual(route.query, item.query);
} else if (item.params) {
return isEqual(route.params, item.params);
} else { } else {
return item.path === route.path; return item.path === route.path;
} }
@@ -117,23 +58,9 @@ const dynamicTagView = () => {
moveToView(index); moveToView(index);
}; };
watch([route], () => {
activeIndex.value = -1;
dynamicTagView();
});
useResizeObserver(
scrollbarDom,
useDebounceFn(() => {
dynamicTagView();
}, 200)
);
const tabNavPadding = 10;
const moveToView = (index: number): void => { const moveToView = (index: number): void => {
if (!instance.refs["dynamic" + index]) { const tabNavPadding = 10;
return; if (!instance.refs["dynamic" + index]) return;
}
const tabItemEl = instance.refs["dynamic" + index][0]; const tabItemEl = instance.refs["dynamic" + index][0];
const tabItemElOffsetLeft = (tabItemEl as HTMLElement)?.offsetLeft; const tabItemElOffsetLeft = (tabItemEl as HTMLElement)?.offsetLeft;
const tabItemOffsetWidth = (tabItemEl as HTMLElement)?.offsetWidth; const tabItemOffsetWidth = (tabItemEl as HTMLElement)?.offsetWidth;
@@ -143,7 +70,9 @@ const moveToView = (index: number): void => {
: 0; : 0;
// 已有标签页总长度(包含溢出部分) // 已有标签页总长度(包含溢出部分)
const tabDomWidth = tabDom.value ? tabDom.value?.offsetWidth : 0; const tabDomWidth = tabDom.value ? tabDom.value?.offsetWidth : 0;
scrollbarDomWidth <= tabDomWidth
? (isShowArrow.value = true)
: (isShowArrow.value = false);
if (tabDomWidth < scrollbarDomWidth || tabItemElOffsetLeft === 0) { if (tabDomWidth < scrollbarDomWidth || tabItemElOffsetLeft === 0) {
translateX.value = 0; translateX.value = 0;
} else if (tabItemElOffsetLeft < -translateX.value) { } else if (tabItemElOffsetLeft < -translateX.value) {
@@ -192,68 +121,6 @@ const handleScroll = (offset: number): void => {
} }
}; };
const tagsViews = reactive<Array<tagsViewsType>>([
{
icon: refresh,
text: $t("buttons.hsreload"),
divided: false,
disabled: false,
show: true
},
{
icon: close,
text: $t("buttons.hscloseCurrentTab"),
divided: false,
disabled: multiTags.value.length > 1 ? false : true,
show: true
},
{
icon: closeLeft,
text: $t("buttons.hscloseLeftTabs"),
divided: true,
disabled: multiTags.value.length > 1 ? false : true,
show: true
},
{
icon: closeRight,
text: $t("buttons.hscloseRightTabs"),
divided: false,
disabled: multiTags.value.length > 1 ? false : true,
show: true
},
{
icon: closeOther,
text: $t("buttons.hscloseOtherTabs"),
divided: true,
disabled: multiTags.value.length > 2 ? false : true,
show: true
},
{
icon: closeAll,
text: $t("buttons.hscloseAllTabs"),
divided: false,
disabled: multiTags.value.length > 1 ? false : true,
show: true
}
]);
// 显示模式,默认灵动模式显示
const showModel = ref(
storageLocal.getItem("responsive-configure")?.showModel || "smart"
);
if (!showModel.value) {
const configure = storageLocal.getItem("responsive-configure");
configure.showModel = "card";
storageLocal.setItem("responsive-configure", configure);
}
let visible = ref(false);
let buttonLeft = ref(0);
let buttonTop = ref(0);
// 当前右键选中的路由信息
let currentSelect = ref({});
function dynamicRouteTag(value: string, parentPath: string): void { function dynamicRouteTag(value: string, parentPath: string): void {
const hasValue = multiTags.value.some(item => { const hasValue = multiTags.value.some(item => {
return item.path === value; return item.path === value;
@@ -278,20 +145,16 @@ function dynamicRouteTag(value: string, parentPath: string): void {
}); });
} }
} }
concatPath(router.options.routes, value, parentPath); concatPath(router.options.routes as any, value, parentPath);
} }
// 重新加载 /** 刷新路由 */
function onFresh() { function onFresh() {
toggleClass(true, refreshButton, document.querySelector(".rotate"));
const { fullPath, query } = unref(route); const { fullPath, query } = unref(route);
router.replace({ router.replace({
path: "/redirect" + fullPath, path: "/redirect" + fullPath,
query: query query: query
}); });
setTimeout(() => {
removeClass(document.querySelector(".rotate"), refreshButton);
}, 600);
} }
function deleteDynamicTag(obj: any, current: any, tag?: string) { function deleteDynamicTag(obj: any, current: any, tag?: string) {
@@ -302,6 +165,10 @@ function deleteDynamicTag(obj: any, current: any, tag?: string) {
if (item.path === obj.path) { if (item.path === obj.path) {
return item.query === obj.query; return item.query === obj.query;
} }
} else if (item.params) {
if (item.path === obj.path) {
return item.params === obj.params;
}
} else { } else {
return item.path === obj.path; return item.path === obj.path;
} }
@@ -313,23 +180,12 @@ function deleteDynamicTag(obj: any, current: any, tag?: string) {
other?: boolean other?: boolean
): void => { ): void => {
if (other) { if (other) {
useMultiTagsStoreHook().handleTags("equal", [ useMultiTagsStoreHook().handleTags("equal", [routerArrays[0], obj]);
{
path: "/welcome",
parentPath: "/",
meta: {
title: "menus.hshome",
icon: "home-filled"
}
},
obj
]);
} else { } else {
// @ts-ignore
delAliveRouteList = useMultiTagsStoreHook().handleTags("splice", "", { delAliveRouteList = useMultiTagsStoreHook().handleTags("splice", "", {
startIndex, startIndex,
length length
}); }) as any;
} }
}; };
@@ -351,24 +207,25 @@ function deleteDynamicTag(obj: any, current: any, tag?: string) {
: handleAliveRoute(route.matched, "delete"); : handleAliveRoute(route.matched, "delete");
// 如果删除当前激活tag就自动切换到最后一个tag // 如果删除当前激活tag就自动切换到最后一个tag
if (tag === "left") return; if (tag === "left") return;
nextTick(() => { if (newRoute[0]?.query) {
router.push({ router.push({ name: newRoute[0].name, query: newRoute[0].query });
path: newRoute[0].path, } else if (newRoute[0]?.params) {
query: newRoute[0].query router.push({ name: newRoute[0].name, params: newRoute[0].params });
}); } else {
}); router.push({ path: newRoute[0].path });
}
} else { } else {
// 删除缓存路由 // 删除缓存路由
tag ? delAliveRoutes(delAliveRouteList) : delAliveRoutes([obj]); tag ? delAliveRoutes(delAliveRouteList) : delAliveRoutes([obj]);
if (!multiTags.value.length) return; if (!multiTags.value.length) return;
let isHasActiveTag = multiTags.value.some(item => { if (multiTags.value.some(item => item.path === route.path)) return;
return item.path === route.path; if (newRoute[0]?.query) {
}); router.push({ name: newRoute[0].name, query: newRoute[0].query });
!isHasActiveTag && } else if (newRoute[0]?.params) {
router.push({ router.push({ name: newRoute[0].name, params: newRoute[0].params });
path: newRoute[0].path, } else {
query: newRoute[0].query router.push({ path: newRoute[0].path });
}); }
} }
} }
@@ -385,7 +242,8 @@ function onClickDrop(key, item, selectRoute?: RouteConfigs) {
path: selectRoute.path, path: selectRoute.path,
meta: selectRoute.meta, meta: selectRoute.meta,
name: selectRoute.name, name: selectRoute.name,
query: selectRoute.query query: selectRoute?.query,
params: selectRoute?.params
}; };
} else { } else {
selectTagRoute = { path: route.path, meta: route.meta }; selectTagRoute = { path: route.path, meta: route.meta };
@@ -394,7 +252,7 @@ function onClickDrop(key, item, selectRoute?: RouteConfigs) {
// 当前路由信息 // 当前路由信息
switch (key) { switch (key) {
case 0: case 0:
// 重新加载 // 刷新路由
onFresh(); onFresh();
break; break;
case 1: case 1:
@@ -419,30 +277,50 @@ function onClickDrop(key, item, selectRoute?: RouteConfigs) {
startIndex: 1, startIndex: 1,
length: multiTags.value.length length: multiTags.value.length
}); });
usePermissionStoreHook().clearAllCachePage();
router.push("/welcome"); router.push("/welcome");
break; 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(() => { setTimeout(() => {
showMenuModel(route.fullPath, route.query); showMenuModel(route.fullPath, route.query);
}); });
} }
function handleCommand(command: object) { function handleCommand(command: any) {
// @ts-expect-error
const { key, item } = command; const { key, item } = command;
onClickDrop(key, item); onClickDrop(key, item);
} }
// 触发右键中菜单的点击事件 /** 触发右键中菜单的点击事件 */
function selectTag(key, item) { function selectTag(key, item) {
onClickDrop(key, item, currentSelect.value); onClickDrop(key, item, currentSelect.value);
} }
function closeMenu() {
visible.value = false;
}
function showMenus(value: boolean) { function showMenus(value: boolean) {
Array.of(1, 2, 3, 4, 5).forEach(v => { Array.of(1, 2, 3, 4, 5).forEach(v => {
tagsViews[v].show = value; tagsViews[v].show = value;
@@ -455,7 +333,7 @@ function disabledMenus(value: boolean) {
}); });
} }
// 检查当前右键的菜单两边是否存在别的菜单,如果左侧的菜单是首页,则不显示关闭左侧标签页,如果右侧没有菜单,则不显示关闭右侧标签页 /** 检查当前右键的菜单两边是否存在别的菜单,如果左侧的菜单是首页,则不显示关闭左侧标签页,如果右侧没有菜单,则不显示关闭右侧标签页 */
function showMenuModel( function showMenuModel(
currentPath: string, currentPath: string,
query: object = {}, query: object = {},
@@ -515,7 +393,7 @@ function openMenu(tag, e) {
// 右键菜单为首页,只显示刷新 // 右键菜单为首页,只显示刷新
showMenus(false); showMenus(false);
tagsViews[0].show = true; tagsViews[0].show = true;
} else if (route.path !== tag.path) { } else if (route.path !== tag.path && route.name !== tag.name) {
// 右键菜单不匹配当前路由,隐藏刷新 // 右键菜单不匹配当前路由,隐藏刷新
tagsViews[0].show = false; tagsViews[0].show = false;
showMenuModel(tag.path, tag.query); showMenuModel(tag.path, tag.query);
@@ -543,63 +421,36 @@ function openMenu(tag, e) {
} else { } else {
buttonLeft.value = left; buttonLeft.value = left;
} }
pureSetting.hiddenSideBar useSettingStoreHook().hiddenSideBar
? (buttonTop.value = e.clientY) ? (buttonTop.value = e.clientY)
: (buttonTop.value = e.clientY - 40); : (buttonTop.value = e.clientY - 40);
setTimeout(() => { nextTick(() => {
visible.value = true; visible.value = true;
}, 10);
}
// 触发tags标签切换
function tagOnClick(item) {
router.push({
path: item?.path,
query: item?.query
}); });
showMenuModel(item?.path, item?.query);
} }
// 鼠标移入 /** 触发tags标签切换 */
function onMouseenter(index) { function tagOnClick(item) {
if (index) activeIndex.value = index; const { name, path } = item;
if (unref(showModel) === "smart") { if (name) {
if (hasClass(instance.refs["schedule" + index][0], "schedule-active")) if (item.query) {
return; router.push({
toggleClass(true, "schedule-in", instance.refs["schedule" + index][0]); name,
toggleClass(false, "schedule-out", instance.refs["schedule" + index][0]); query: item.query
} else { });
if (hasClass(instance.refs["dynamic" + index][0], "card-active")) return; } else if (item.params) {
toggleClass(true, "card-in", instance.refs["dynamic" + index][0]); router.push({
toggleClass(false, "card-out", instance.refs["dynamic" + index][0]); name,
} params: item.params
} });
// 鼠标移出
function onMouseleave(index) {
activeIndex.value = -1;
if (unref(showModel) === "smart") {
if (hasClass(instance.refs["schedule" + index][0], "schedule-active"))
return;
toggleClass(false, "schedule-in", instance.refs["schedule" + index][0]);
toggleClass(true, "schedule-out", instance.refs["schedule" + index][0]);
} else {
if (hasClass(instance.refs["dynamic" + index][0], "card-active")) return;
toggleClass(false, "card-in", instance.refs["dynamic" + index][0]);
toggleClass(true, "card-out", instance.refs["dynamic" + index][0]);
}
}
watch(
() => visible.value,
val => {
if (val) {
document.body.addEventListener("click", closeMenu);
} else { } else {
document.body.removeEventListener("click", closeMenu); router.push({ name });
} }
} else {
router.push({ path });
} }
); // showMenuModel(item?.path, item?.query);
}
onBeforeMount(() => { onBeforeMount(() => {
if (!instance) return; if (!instance) return;
@@ -608,9 +459,9 @@ onBeforeMount(() => {
showMenuModel(route.fullPath); showMenuModel(route.fullPath);
// 触发隐藏标签页 // 触发隐藏标签页
emitter.on("tagViewsChange", key => { emitter.on("tagViewsChange", (key: any) => {
if (unref(showTags) === key) return; if (unref(showTags as any) === key) return;
showTags.value = key; (showTags as any).value = key;
}); });
// 改变标签风格 // 改变标签风格
@@ -627,22 +478,26 @@ onBeforeMount(() => {
}); });
}); });
const getTabStyle = computed((): CSSProperties => { watch([route], () => {
return { activeIndex.value = -1;
transform: `translateX(${translateX.value}px)` dynamicTagView();
};
}); });
const getContextMenuStyle = computed((): CSSProperties => { onMounted(() => {
return { left: buttonLeft.value + "px", top: buttonTop.value + "px" }; useResizeObserver(
scrollbarDom,
useDebounceFn(() => {
dynamicTagView();
}, 200)
);
}); });
</script> </script>
<template> <template>
<div ref="containerDom" class="tags-view" v-if="!showTags"> <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)" /> <IconifyIconOffline icon="arrow-left-s-line" @click="handleScroll(200)" />
</div> </span>
<div ref="scrollbarDom" class="scroll-container"> <div ref="scrollbarDom" class="scroll-container">
<div class="tab" ref="tabDom" :style="getTabStyle"> <div class="tab" ref="tabDom" :style="getTabStyle">
<div <div
@@ -661,8 +516,11 @@ const getContextMenuStyle = computed((): CSSProperties => {
@mouseleave.prevent="onMouseleave(index)" @mouseleave.prevent="onMouseleave(index)"
@click="tagOnClick(item)" @click="tagOnClick(item)"
> >
<router-link :to="item.path" <router-link
>{{ transformI18n(item.meta.title) }} :to="item.path"
class="dark:!text-text_color_primary dark:hover:!text-primary"
>
{{ transformI18n(item.meta.title) }}
</router-link> </router-link>
<span <span
v-if=" v-if="
@@ -682,7 +540,7 @@ const getContextMenuStyle = computed((): CSSProperties => {
</div> </div>
</div> </div>
</div> </div>
<span class="arrow-right"> <span v-show="isShowArrow" class="arrow-right">
<IconifyIconOffline <IconifyIconOffline
icon="arrow-right-s-line" icon="arrow-right-s-line"
@click="handleScroll(-200)" @click="handleScroll(-200)"
@@ -697,59 +555,41 @@ const getContextMenuStyle = computed((): CSSProperties => {
class="contextmenu" class="contextmenu"
> >
<div <div
v-for="(item, key) in tagsViews" v-for="(item, key) in tagsViews.slice(0, 6)"
:key="key" :key="key"
style="display: flex; align-items: center" style="display: flex; align-items: center"
> >
<li v-if="item.show" @click="selectTag(key, item)"> <li v-if="item.show" @click="selectTag(key, item)">
<component :is="toRaw(item.icon)" :key="key" /> <IconifyIconOffline :icon="item.icon" />
{{ t(item.text) }} {{ transformI18n(item.text) }}
</li> </li>
</div> </div>
</ul> </ul>
</transition> </transition>
<!-- 右侧功能按钮 --> <!-- 右侧功能按钮 -->
<ul class="right-button"> <el-dropdown
<li> trigger="click"
<span placement="bottom-end"
:title="t('buttons.hsrefreshRoute')" @command="handleCommand"
class="el-icon-refresh-right rotate" >
@click="onFresh" <span class="arrow-down">
> <IconifyIconOffline icon="arrow-down" class="dark:text-white" />
<IconifyIconOffline icon="refresh-right" /> </span>
</span> <template #dropdown>
</li> <el-dropdown-menu>
<li> <el-dropdown-item
<el-dropdown v-for="(item, key) in tagsViews"
trigger="click" :key="key"
placement="bottom-end" :command="{ key, item }"
@command="handleCommand" :divided="item.divided"
> :disabled="item.disabled"
<IconifyIconOffline icon="arrow-down" /> >
<template #dropdown> <IconifyIconOffline :icon="item.icon" />
<el-dropdown-menu> {{ transformI18n(item.text) }}
<el-dropdown-item </el-dropdown-item>
v-for="(item, key) in tagsViews" </el-dropdown-menu>
:key="key" </template>
:command="{ key, item }" </el-dropdown>
:divided="item.divided"
:disabled="item.disabled"
>
<component
:is="toRaw(item.icon)"
:key="key"
style="margin-right: 6px"
/>
{{ t(item.text) }}
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</li>
<li>
<slot />
</li>
</ul>
</div> </div>
</template> </template>

View File

@@ -1,20 +1,14 @@
<template>
<div
class="frame"
v-loading="loading"
:element-loading-text="t('status.hsLoad')"
>
<iframe :src="frameSrc" class="frame-iframe" ref="frameRef" />
</div>
</template>
<script lang="ts" setup> <script lang="ts" setup>
import { useI18n } from "vue-i18n"; import { useI18n } from "vue-i18n";
import { useRoute } from "vue-router"; import { useRoute } from "vue-router";
import { ref, unref, onMounted, nextTick } from "vue"; import { ref, unref, onMounted, nextTick } from "vue";
defineOptions({
name: "FrameView"
});
const { t } = useI18n(); const { t } = useI18n();
const loading = ref(false); const loading = ref(true);
const currentRoute = useRoute(); const currentRoute = useRoute();
const frameSrc = ref<string>(""); const frameSrc = ref<string>("");
const frameRef = ref<HTMLElement | null>(null); const frameRef = ref<HTMLElement | null>(null);
@@ -22,6 +16,7 @@ const frameRef = ref<HTMLElement | null>(null);
if (unref(currentRoute.meta)?.frameSrc) { if (unref(currentRoute.meta)?.frameSrc) {
frameSrc.value = unref(currentRoute.meta)?.frameSrc as string; frameSrc.value = unref(currentRoute.meta)?.frameSrc as string;
} }
unref(currentRoute.meta)?.frameLoading === false && hideLoading();
function hideLoading() { function hideLoading() {
loading.value = false; loading.value = false;
@@ -45,11 +40,20 @@ function init() {
} }
onMounted(() => { onMounted(() => {
loading.value = true;
init(); init();
}); });
</script> </script>
<template>
<div
class="frame"
v-loading="loading"
:element-loading-text="t('status.hsLoad')"
>
<iframe :src="frameSrc" class="frame-iframe" ref="frameRef" />
</div>
</template>
<style lang="scss" scoped> <style lang="scss" scoped>
.frame { .frame {
height: calc(100vh - 88px); height: calc(100vh - 88px);

View File

@@ -1,6 +1,6 @@
import { ref } from "vue"; import { ref } from "vue";
export default function useBoolean(initValue = false) { export function useBoolean(initValue = false) {
const bool = ref(initValue); const bool = ref(initValue);
function setBool(value: boolean) { function setBool(value: boolean) {

View File

@@ -0,0 +1,116 @@
import { ref } from "vue";
import { getConfig } from "/@/config";
import { find } from "lodash-unified";
import { useLayout } from "./useLayout";
import { themeColorsType } from "../types";
import { TinyColor } from "@ctrl/tinycolor";
import { useGlobal } from "@pureadmin/utils";
import { useEpThemeStoreHook } from "/@/store/modules/epTheme";
import {
darken,
lighten,
toggleTheme
} from "@pureadmin/theme/dist/browser-utils";
export function useDataThemeChange() {
const { layoutTheme, layout } = useLayout();
const themeColors = ref<Array<themeColorsType>>([
/* 道奇蓝(默认) */
{ color: "#1b2a47", themeColor: "default" },
/* 亮白色 */
{ color: "#ffffff", themeColor: "light" },
/* 猩红色 */
{ color: "#f5222d", themeColor: "dusk" },
/* 橙红色 */
{ color: "#fa541c", themeColor: "volcano" },
/* 金色 */
{ color: "#fadb14", themeColor: "yellow" },
/* 绿宝石 */
{ color: "#13c2c2", themeColor: "mingQing" },
/* 酸橙绿 */
{ color: "#52c41a", themeColor: "auroraGreen" },
/* 深粉色 */
{ color: "#eb2f96", themeColor: "pink" },
/* 深紫罗兰色 */
{ color: "#722ed1", themeColor: "saucePurple" }
]);
const { $storage } = useGlobal<GlobalPropertiesApi>();
const dataTheme = ref<boolean>($storage?.layout?.darkMode);
const body = document.documentElement as HTMLElement;
/** 设置导航主题色 */
function setLayoutThemeColor(theme = "default") {
layoutTheme.value.theme = theme;
toggleTheme({
scopeName: `layout-theme-${theme}`
});
$storage.layout = {
layout: layout.value,
theme,
darkMode: dataTheme.value,
sidebarStatus: $storage.layout?.sidebarStatus,
epThemeColor: $storage.layout?.epThemeColor
};
if (theme === "default" || theme === "light") {
setEpThemeColor(getConfig().EpThemeColor);
} else {
const colors = find(themeColors.value, { themeColor: theme });
setEpThemeColor(colors.color);
}
}
/**
* @description 自动计算hover和active颜色
* @see {@link https://element-plus.org/zh-CN/component/button.html#%E8%87%AA%E5%AE%9A%E4%B9%89%E9%A2%9C%E8%89%B2}
*/
const shadeBgColor = (color: string): string => {
return new TinyColor(color).shade(10).toString();
};
/** 设置ep主题色 */
const setEpThemeColor = (color: string) => {
useEpThemeStoreHook().setEpThemeColor(color);
body.style.setProperty("--el-color-primary-active", shadeBgColor(color));
document.documentElement.style.setProperty("--el-color-primary", color);
for (let i = 1; i <= 9; i++) {
document.documentElement.style.setProperty(
`--el-color-primary-light-${i}`,
lighten(color, i / 10)
);
}
for (let i = 1; i <= 2; i++) {
document.documentElement.style.setProperty(
`--el-color-primary-dark-${i}`,
darken(color, i / 10)
);
}
};
/** 日间、夜间主题切换 */
function dataThemeChange() {
/* 如果当前是light夜间主题默认切换到default主题 */
if (useEpThemeStoreHook().epTheme === "light" && dataTheme.value) {
setLayoutThemeColor("default");
} else {
setLayoutThemeColor(useEpThemeStoreHook().epTheme);
}
if (dataTheme.value) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
}
return {
body,
dataTheme,
layoutTheme,
themeColors,
dataThemeChange,
setEpThemeColor,
setLayoutThemeColor
};
}

View File

@@ -0,0 +1,60 @@
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { routerArrays } from "../types";
import { useGlobal } from "@pureadmin/utils";
import { useMultiTagsStore } from "/@/store/modules/multiTags";
export function useLayout() {
const { $storage, $config } = useGlobal<GlobalPropertiesApi>();
const initStorage = () => {
/** 路由 */
if (
useMultiTagsStore().multiTagsCache &&
(!$storage.tags || $storage.tags.length === 0)
) {
$storage.tags = routerArrays;
}
/** 国际化 */
if (!$storage.locale) {
$storage.locale = { locale: $config?.Locale ?? "zh" };
useI18n().locale.value = $config?.Locale ?? "zh";
}
/** 导航 */
if (!$storage.layout) {
$storage.layout = {
layout: $config?.Layout ?? "vertical",
theme: $config?.Theme ?? "default",
darkMode: $config?.DarkMode ?? false,
sidebarStatus: $config?.SidebarStatus ?? true,
epThemeColor: $config?.EpThemeColor ?? "#409EFF"
};
}
/** 灰色模式、色弱模式、隐藏标签页 */
if (!$storage.configure) {
$storage.configure = {
grey: $config?.Grey ?? false,
weak: $config?.Weak ?? false,
hideTabs: $config?.HideTabs ?? false,
showLogo: $config?.ShowLogo ?? true,
showModel: $config?.ShowModel ?? "smart",
multiTagsCache: $config?.MultiTagsCache ?? false
};
}
};
/** 清空缓存后从serverConfig.json读取默认配置并赋值到storage中 */
const layout = computed(() => {
return $storage?.layout.layout;
});
const layoutTheme = computed(() => {
return $storage.layout;
});
return {
layout,
layoutTheme,
initStorage
};
}

View File

@@ -1,22 +1,27 @@
import { computed } from "vue"; import { computed } from "vue";
import { router } from "/@/router";
import { getConfig } from "/@/config"; import { getConfig } from "/@/config";
import { useRouter } from "vue-router";
import { emitter } from "/@/utils/mitt"; import { emitter } from "/@/utils/mitt";
import { routeMetaType } from "../types"; import { routeMetaType } from "../types";
import { remainingPaths } from "/@/router"; import { useGlobal } from "@pureadmin/utils";
import { transformI18n } from "/@/plugins/i18n"; import { transformI18n } from "/@/plugins/i18n";
import { storageSession } from "/@/utils/storage"; import { router, remainingPaths } from "/@/router";
import { useAppStoreHook } from "/@/store/modules/app"; import { useAppStoreHook } from "/@/store/modules/app";
import { useUserStoreHook } from "/@/store/modules/user";
import { useEpThemeStoreHook } from "/@/store/modules/epTheme"; import { useEpThemeStoreHook } from "/@/store/modules/epTheme";
const errorInfo = "当前路由配置不正确,请检查配置"; const errorInfo = "当前路由配置不正确,请检查配置";
export function useNav() { export function useNav() {
const pureApp = useAppStoreHook(); const pureApp = useAppStoreHook();
// 用户名 const routers = useRouter().options.routes;
const username: string = storageSession.getItem("info")?.username;
// 设置国际化选中后的样式 /** 用户名 */
const username = computed(() => {
return useUserStoreHook()?.username;
});
/** 设置国际化选中后的样式 */
const getDropdownItemStyle = computed(() => { const getDropdownItemStyle = computed(() => {
return (locale, t) => { return (locale, t) => {
return { return {
@@ -26,25 +31,43 @@ export function useNav() {
}; };
}); });
const getDropdownItemClass = computed(() => {
return (locale, t) => {
return locale === t ? "" : "dark:hover:!text-primary";
};
});
const avatarsStyle = computed(() => { const avatarsStyle = computed(() => {
return username ? { marginRight: "10px" } : ""; return username.value ? { marginRight: "10px" } : "";
}); });
const isCollapse = computed(() => { const isCollapse = computed(() => {
return !pureApp.getSidebarStatus; return !pureApp.getSidebarStatus;
}); });
// 动态title const device = computed(() => {
return pureApp.getDevice;
});
const { $storage, $config } = useGlobal<GlobalPropertiesApi>();
const layout = computed(() => {
return $storage?.layout?.layout;
});
const title = computed(() => {
return $config.Title;
});
/** 动态title */
function changeTitle(meta: routeMetaType) { function changeTitle(meta: routeMetaType) {
const Title = getConfig().Title; const Title = getConfig().Title;
if (Title) document.title = `${transformI18n(meta.title)} | ${Title}`; if (Title) document.title = `${transformI18n(meta.title)} | ${Title}`;
else document.title = transformI18n(meta.title); else document.title = transformI18n(meta.title);
} }
// 退出登录 /** 退出登录 */
function logout() { function logout() {
storageSession.removeItem("info"); useUserStoreHook().logOut();
router.push("/login");
} }
function backHome() { function backHome() {
@@ -60,7 +83,7 @@ export function useNav() {
} }
function handleResize(menuRef) { function handleResize(menuRef) {
menuRef.handleResize(); menuRef?.handleResize();
} }
function resolvePath(route) { function resolvePath(route) {
@@ -81,7 +104,7 @@ export function useNav() {
if (parentPathIndex > 0) { if (parentPathIndex > 0) {
parentPath = indexPath.slice(0, parentPathIndex); parentPath = indexPath.slice(0, parentPathIndex);
} }
// 找到当前路由的信息 /** 找到当前路由的信息 */
function findCurrentRoute(indexPath: string, routes) { function findCurrentRoute(indexPath: string, routes) {
if (!routes) return console.error(errorInfo); if (!routes) return console.error(errorInfo);
return routes.map(item => { return routes.map(item => {
@@ -89,7 +112,7 @@ export function useNav() {
if (item.redirect) { if (item.redirect) {
findCurrentRoute(item.redirect, item.children); findCurrentRoute(item.redirect, item.children);
} else { } else {
// 切换左侧菜单 通知标签页 /** 切换左侧菜单 通知标签页 */
emitter.emit("changLayoutRoute", { emitter.emit("changLayoutRoute", {
indexPath, indexPath,
parentPath parentPath
@@ -103,13 +126,18 @@ export function useNav() {
findCurrentRoute(indexPath, routers); findCurrentRoute(indexPath, routers);
} }
// 判断路径是否参与菜单 /** 判断路径是否参与菜单 */
function isRemaining(path: string): boolean { function isRemaining(path: string): boolean {
return remainingPaths.includes(path); return remainingPaths.includes(path);
} }
return { return {
title,
device,
layout,
logout, logout,
routers,
$storage,
backHome, backHome,
onPanel, onPanel,
changeTitle, changeTitle,
@@ -121,6 +149,7 @@ export function useNav() {
pureApp, pureApp,
username, username,
avatarsStyle, avatarsStyle,
getDropdownItemStyle getDropdownItemStyle,
getDropdownItemClass
}; };
} }

235
src/layout/hooks/useTag.ts Normal file
View File

@@ -0,0 +1,235 @@
import {
ref,
unref,
watch,
computed,
reactive,
onMounted,
CSSProperties,
getCurrentInstance
} from "vue";
import { tagsViewsType } from "../types";
import { isEqual } from "lodash-unified";
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";
export function useTags() {
const route = useRoute();
const router = useRouter();
const instance = getCurrentInstance();
const pureSetting = useSettingStoreHook();
const buttonTop = ref(0);
const buttonLeft = ref(0);
const translateX = ref(0);
const visible = ref(false);
const activeIndex = ref(-1);
// 当前右键选中的路由信息
const currentSelect = ref({});
/** 显示模式,默认灵动模式 */
const showModel = ref(
storageLocal.getItem<StorageConfigs>("responsive-configure")?.showModel ||
"smart"
);
/** 是否隐藏标签页,默认显示 */
const showTags =
ref(
storageLocal.getItem<StorageConfigs>("responsive-configure").hideTabs
) ?? ref("false");
const multiTags: any = computed(() => {
return useMultiTagsStoreHook().multiTags;
});
const tagsViews = reactive<Array<tagsViewsType>>([
{
icon: "refresh-right",
text: $t("buttons.hsreload"),
divided: false,
disabled: false,
show: true
},
{
icon: "close",
text: $t("buttons.hscloseCurrentTab"),
divided: false,
disabled: multiTags.value.length > 1 ? false : true,
show: true
},
{
icon: "close-left-tags",
text: $t("buttons.hscloseLeftTabs"),
divided: true,
disabled: multiTags.value.length > 1 ? false : true,
show: true
},
{
icon: "close-right-tags",
text: $t("buttons.hscloseRightTabs"),
divided: false,
disabled: multiTags.value.length > 1 ? false : true,
show: true
},
{
icon: "close-other-tags",
text: $t("buttons.hscloseOtherTabs"),
divided: true,
disabled: multiTags.value.length > 2 ? false : true,
show: true
},
{
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
}
]);
function conditionHandle(item, previous, next) {
if (
Object.keys(route.query).length === 0 &&
Object.keys(route.params).length === 0
) {
return route.path === item.path ? previous : next;
} else if (Object.keys(route.query).length > 0) {
return isEqual(route.query, item.query) ? previous : next;
} else {
return isEqual(route.params, item.params) ? previous : next;
}
}
const iconIsActive = computed(() => {
return (item, index) => {
if (index === 0) return;
return conditionHandle(item, true, false);
};
});
const linkIsActive = computed(() => {
return item => {
return conditionHandle(item, "is-active", "");
};
});
const scheduleIsActive = computed(() => {
return item => {
return conditionHandle(item, "schedule-active", "");
};
});
const getTabStyle = computed((): CSSProperties => {
return {
transform: `translateX(${translateX.value}px)`
};
});
const getContextMenuStyle = computed((): CSSProperties => {
return { left: buttonLeft.value + "px", top: buttonTop.value + "px" };
});
const closeMenu = () => {
visible.value = false;
};
/** 鼠标移入添加激活样式 */
function onMouseenter(index) {
if (index) activeIndex.value = index;
if (unref(showModel) === "smart") {
if (hasClass(instance.refs["schedule" + index][0], "schedule-active"))
return;
toggleClass(true, "schedule-in", instance.refs["schedule" + index][0]);
toggleClass(false, "schedule-out", instance.refs["schedule" + index][0]);
} else {
if (hasClass(instance.refs["dynamic" + index][0], "card-active")) return;
toggleClass(true, "card-in", instance.refs["dynamic" + index][0]);
toggleClass(false, "card-out", instance.refs["dynamic" + index][0]);
}
}
/** 鼠标移出恢复默认样式 */
function onMouseleave(index) {
activeIndex.value = -1;
if (unref(showModel) === "smart") {
if (hasClass(instance.refs["schedule" + index][0], "schedule-active"))
return;
toggleClass(false, "schedule-in", instance.refs["schedule" + index][0]);
toggleClass(true, "schedule-out", instance.refs["schedule" + index][0]);
} else {
if (hasClass(instance.refs["dynamic" + index][0], "card-active")) return;
toggleClass(false, "card-in", instance.refs["dynamic" + index][0]);
toggleClass(true, "card-out", instance.refs["dynamic" + index][0]);
}
}
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>(
"responsive-configure"
);
configure.showModel = "card";
storageLocal.setItem("responsive-configure", configure);
}
});
watch(
() => visible.value,
() => {
useEventListener(document, "click", closeMenu);
}
);
return {
route,
router,
visible,
showTags,
instance,
multiTags,
showModel,
tagsViews,
buttonTop,
buttonLeft,
translateX,
pureSetting,
activeIndex,
getTabStyle,
iconIsActive,
linkIsActive,
currentSelect,
scheduleIsActive,
getContextMenuStyle,
$t,
closeMenu,
onMounted,
onMouseenter,
onMouseleave,
transformI18n,
onContentFullScreen
};
}

View File

@@ -0,0 +1,37 @@
import { useNav } from "./useNav";
import { useI18n } from "vue-i18n";
import { useRoute } from "vue-router";
import { watch, type Ref } from "vue";
export function useTranslationLang(ref?: Ref) {
const { $storage, changeTitle, handleResize } = useNav();
const { locale, t } = useI18n();
const route = useRoute();
function translationCh() {
$storage.locale = { locale: "zh" };
locale.value = "zh";
ref && handleResize(ref.value);
}
function translationEn() {
$storage.locale = { locale: "en" };
locale.value = "en";
ref && handleResize(ref.value);
}
watch(
() => locale.value,
() => {
changeTitle(route.meta);
}
);
return {
t,
route,
locale,
translationCh,
translationEn
};
}

View File

@@ -1,24 +1,11 @@
<script setup lang="ts"> <script setup lang="ts">
import {
h,
reactive,
computed,
onMounted,
defineComponent,
getCurrentInstance
} from "vue";
import { setType } from "./types"; import { setType } from "./types";
import { useI18n } from "vue-i18n";
import { routerArrays } from "./types";
import { emitter } from "/@/utils/mitt"; import { emitter } from "/@/utils/mitt";
import { useLayout } from "./hooks/useLayout";
import { useAppStoreHook } from "/@/store/modules/app"; import { useAppStoreHook } from "/@/store/modules/app";
import { deviceDetection } from "/@/utils/deviceDetection";
import { useMultiTagsStore } from "/@/store/modules/multiTags";
import { useSettingStoreHook } from "/@/store/modules/settings"; import { useSettingStoreHook } from "/@/store/modules/settings";
import { deviceDetection, useDark, useGlobal } from "@pureadmin/utils";
import backTop from "/@/assets/svg/back_top.svg?component"; import { h, reactive, computed, onMounted, defineComponent } from "vue";
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 navbar from "./components/navbar.vue";
import tag from "./components/tag/index.vue"; import tag from "./components/tag/index.vue";
@@ -26,52 +13,13 @@ import appMain from "./components/appMain.vue";
import setting from "./components/setting/index.vue"; import setting from "./components/setting/index.vue";
import Vertical from "./components/sidebar/vertical.vue"; import Vertical from "./components/sidebar/vertical.vue";
import Horizontal from "./components/sidebar/horizontal.vue"; import Horizontal from "./components/sidebar/horizontal.vue";
import backTop from "/@/assets/svg/back_top.svg?component";
const { isDark } = useDark();
const { layout } = useLayout();
const isMobile = deviceDetection(); const isMobile = deviceDetection();
const pureSetting = useSettingStoreHook(); const pureSetting = useSettingStoreHook();
const instance = getCurrentInstance().appContext.app.config.globalProperties; const { $storage } = useGlobal<GlobalPropertiesApi>();
// 清空缓存后从serverConfig.json读取默认配置并赋值到storage中
const layout = computed(() => {
// 路由
if (
useMultiTagsStore().multiTagsCache &&
(!instance.$storage.tags || instance.$storage.tags.length === 0)
) {
// eslint-disable-next-line vue/no-side-effects-in-computed-properties
instance.$storage.tags = routerArrays;
}
// 国际化
if (!instance.$storage.locale) {
// eslint-disable-next-line
instance.$storage.locale = { locale: instance.$config?.Locale ?? "zh" };
useI18n().locale.value = instance.$config?.Locale ?? "zh";
}
// 导航
if (!instance.$storage.layout) {
// eslint-disable-next-line vue/no-side-effects-in-computed-properties
instance.$storage.layout = {
layout: instance.$config?.Layout ?? "vertical",
theme: instance.$config?.Theme ?? "default",
darkMode: instance.$config?.DarkMode ?? false,
sidebarStatus: instance.$config?.SidebarStatus ?? true,
epThemeColor: instance.$config?.EpThemeColor ?? "#409EFF"
};
}
// 灰色模式、色弱模式、隐藏标签页
if (!instance.$storage.configure) {
// eslint-disable-next-line
instance.$storage.configure = {
grey: instance.$config?.Grey ?? false,
weak: instance.$config?.Weak ?? false,
hideTabs: instance.$config?.HideTabs ?? false,
showLogo: instance.$config?.ShowLogo ?? true,
showModel: instance.$config?.ShowModel ?? "smart",
multiTagsCache: instance.$config?.MultiTagsCache ?? false
};
}
return instance.$storage?.layout.layout;
});
const set: setType = reactive({ const set: setType = reactive({
sidebar: computed(() => { sidebar: computed(() => {
@@ -96,18 +44,18 @@ const set: setType = reactive({
}), }),
hideTabs: computed(() => { hideTabs: computed(() => {
return instance.$storage?.configure.hideTabs; return $storage?.configure.hideTabs;
}) })
}); });
function setTheme(layoutModel: string) { function setTheme(layoutModel: string) {
window.document.body.setAttribute("layout", layoutModel); window.document.body.setAttribute("layout", layoutModel);
instance.$storage.layout = { $storage.layout = {
layout: `${layoutModel}`, layout: `${layoutModel}`,
theme: instance.$storage.layout?.theme, theme: $storage.layout?.theme,
darkMode: instance.$storage.layout?.darkMode, darkMode: $storage.layout?.darkMode,
sidebarStatus: instance.$storage.layout?.sidebarStatus, sidebarStatus: $storage.layout?.sidebarStatus,
epThemeColor: instance.$storage.layout?.epThemeColor epThemeColor: $storage.layout?.epThemeColor
}; };
} }
@@ -123,7 +71,7 @@ let isAutoCloseSidebar = true;
emitter.on("resize", ({ detail }) => { emitter.on("resize", ({ detail }) => {
if (isMobile) return; if (isMobile) return;
let { width } = detail; let { width } = detail;
width <= 670 ? setTheme("vertical") : setTheme(useAppStoreHook().layout); width <= 760 ? setTheme("vertical") : setTheme(useAppStoreHook().layout);
/** width app-wrapper类容器宽度 /** width app-wrapper类容器宽度
* 0 < width <= 760 隐藏侧边栏 * 0 < width <= 760 隐藏侧边栏
* 760 < width <= 990 折叠侧边栏 * 760 < width <= 990 折叠侧边栏
@@ -138,7 +86,7 @@ emitter.on("resize", ({ detail }) => {
isAutoCloseSidebar = false; isAutoCloseSidebar = false;
} }
} else if (width > 990) { } else if (width > 990) {
if (!set.sidebar.isClickHamburger) { if (!set.sidebar.isClickCollapse) {
toggle("desktop", true); toggle("desktop", true);
isAutoCloseSidebar = true; isAutoCloseSidebar = true;
} }
@@ -151,12 +99,6 @@ onMounted(() => {
} }
}); });
function onFullScreen() {
pureSetting.hiddenSideBar
? pureSetting.changeSetting({ key: "hiddenSideBar", value: false })
: pureSetting.changeSetting({ key: "hiddenSideBar", value: true });
}
const layoutHeader = defineComponent({ const layoutHeader = defineComponent({
render() { render() {
return h( return h(
@@ -165,7 +107,9 @@ const layoutHeader = defineComponent({
class: { "fixed-header": set.fixedHeader }, class: { "fixed-header": set.fixedHeader },
style: [ style: [
set.hideTabs && layout.value.includes("horizontal") set.hideTabs && layout.value.includes("horizontal")
? "box-shadow: 0 1px 4px rgb(0 21 41 / 8%);" ? isDark.value
? "box-shadow: 0 1px 4px #0d0d0d"
: "box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08)"
: "" : ""
] ]
}, },
@@ -174,27 +118,11 @@ const layoutHeader = defineComponent({
!pureSetting.hiddenSideBar && !pureSetting.hiddenSideBar &&
(layout.value.includes("vertical") || layout.value.includes("mix")) (layout.value.includes("vertical") || layout.value.includes("mix"))
? h(navbar) ? h(navbar)
: h("div"), : null,
!pureSetting.hiddenSideBar && layout.value.includes("horizontal") !pureSetting.hiddenSideBar && layout.value.includes("horizontal")
? h(Horizontal) ? h(Horizontal)
: h("div"), : null,
h( h(tag)
tag,
{},
{
default: () => [
h(
"span",
{ onClick: onFullScreen },
{
default: () => [
!pureSetting.hiddenSideBar ? h(fullScreen) : h(exitScreen)
]
}
)
]
}
)
] ]
} }
); );
@@ -234,7 +162,8 @@ const layoutHeader = defineComponent({
<el-backtop <el-backtop
title="回到顶部" title="回到顶部"
target=".main-container .el-scrollbar__wrap" target=".main-container .el-scrollbar__wrap"
><backTop /> >
<backTop />
</el-backtop> </el-backtop>
<layout-header /> <layout-header />
<!-- 主体内容 --> <!-- 主体内容 -->
@@ -268,10 +197,6 @@ const layoutHeader = defineComponent({
} }
} }
.main-hidden {
margin-left: 0 !important;
}
.app-mask { .app-mask {
background: #000; background: #000;
opacity: 0.3; opacity: 0.3;

View File

@@ -2,6 +2,10 @@
import { unref } from "vue"; import { unref } from "vue";
import { useRouter } from "vue-router"; import { useRouter } from "vue-router";
defineOptions({
name: "Redirect"
});
const { currentRoute, replace } = useRouter(); const { currentRoute, replace } = useRouter();
const { params, query } = unref(currentRoute); const { params, query } = unref(currentRoute);

View File

@@ -1,84 +0,0 @@
/* 动态改变element-plus主题色 */
import rgbHex from "rgb-hex";
import epCss from "./element.scss";
import { TinyColor } from "@ctrl/tinycolor";
import { convert } from "css-color-function";
// 色值表
const formula = {
"shade-1": "color(primary shade(10%))",
"light-1": "color(primary tint(10%))",
"light-2": "color(primary tint(20%))",
"light-3": "color(primary tint(30%))",
"light-4": "color(primary tint(40%))",
"light-5": "color(primary tint(50%))",
"light-6": "color(primary tint(60%))",
"light-7": "color(primary tint(70%))",
"light-8": "color(primary tint(80%))",
"light-9": "color(primary tint(90%))"
};
// 把生成的样式表写入到style中
export const writeNewStyle = (newStyle: string): void => {
const style = window.document.createElement("style");
style.innerText = newStyle;
window.document.head.appendChild(style);
};
// 根据主题色,生成最新的样式表
export const createNewStyle = (
primaryStyle: Record<string, any>
): Record<string, any> => {
// 根据主色生成色值表
const colors = createColors(primaryStyle);
// 在当前ep的默认样式表中标记需要替换的色值
let cssText = getStyleTemplate(epCss);
// 遍历生成的色值表,在 默认样式表 进行全局替换
Object.keys(colors).forEach(key => {
cssText = cssText.replace(
new RegExp("(:|\\s+)" + key, "g"),
"$1" + colors[key]
);
});
return cssText;
};
export const createColors = (
primary: Record<string, any>
): Record<string, any> => {
if (!primary) return;
const colors = {
primary
};
Object.keys(formula).forEach(key => {
const value = formula[key].replace(/primary/, primary);
colors[key] = "#" + rgbHex(convert(value));
});
return colors;
};
const getStyleTemplate = (data: Record<string, any>): Record<string, any> => {
const colorMap = {
"#3a8ee6": "shade-1",
"#409eff": "primary",
"#53a8ff": "light-1",
"#66b1ff": "light-2",
"#79bbff": "light-3",
"#8cc5ff": "light-4",
"#a0cfff": "light-5",
"#b3d8ff": "light-6",
"#c6e2ff": "light-7",
"#d9ecff": "light-8",
"#ecf5ff": "light-9"
};
Object.keys(colorMap).forEach(key => {
const value = colorMap[key];
data = data.replace(new RegExp(key, "ig"), value);
});
return data;
};
// 自动计算hover和active颜色 https://element-plus.gitee.io/zh-CN/component/button.html#%E8%87%AA%E5%AE%9A%E4%B9%89%E9%A2%9C%E8%89%B2-%E6%B5%8B%E8%AF%95%E7%89%88
export const shadeBgColor = (color: string): string => {
return new TinyColor(color).shade(10).toString();
};

View File

@@ -1,2 +0,0 @@
/* 通过scss模块本地导入element-plus的全局样式文件解决vite2.7.13版本后使用 import epCss from "element-plus/dist/index.css",打包后加载不到样式的问题 */
@import "element-plus/dist/index.css";

View File

@@ -1,6 +1,20 @@
/**
* @description ⚠️:此文件仅供主题插件使用,请不要在此文件中导出别的工具函数(仅在页面加载前运行)
*/
import { EpThemeColor } from "../../../public/serverConfig.json";
type MultipleScopeVarsItem = {
scopeName: string;
varsContent: string;
};
/** 将vxe默认主题色和ep默认主题色保持一致 */
const vxeColor = EpThemeColor;
/** 预设主题色 */
const themeColors = { const themeColors = {
default: { default: {
color: "#409EFF", vxeColor,
subMenuActiveText: "#fff", subMenuActiveText: "#fff",
menuBg: "#001529", menuBg: "#001529",
menuHover: "#4091f7", menuHover: "#4091f7",
@@ -13,7 +27,7 @@ const themeColors = {
menuActiveBefore: "#4091f7" menuActiveBefore: "#4091f7"
}, },
light: { light: {
color: "#409EFF", vxeColor,
subMenuActiveText: "#409eff", subMenuActiveText: "#409eff",
menuBg: "#fff", menuBg: "#fff",
menuHover: "#e0ebf6", menuHover: "#e0ebf6",
@@ -26,7 +40,7 @@ const themeColors = {
menuActiveBefore: "#4091f7" menuActiveBefore: "#4091f7"
}, },
dusk: { dusk: {
color: "#f5222d", vxeColor: "#f5222d",
subMenuActiveText: "#fff", subMenuActiveText: "#fff",
menuBg: "#2a0608", menuBg: "#2a0608",
menuHover: "#e13c39", menuHover: "#e13c39",
@@ -39,7 +53,7 @@ const themeColors = {
menuActiveBefore: "#e13c39" menuActiveBefore: "#e13c39"
}, },
volcano: { volcano: {
color: "#fa541c", vxeColor: "#fa541c",
subMenuActiveText: "#fff", subMenuActiveText: "#fff",
menuBg: "#2b0e05", menuBg: "#2b0e05",
menuHover: "#e85f33", menuHover: "#e85f33",
@@ -52,7 +66,7 @@ const themeColors = {
menuActiveBefore: "#e85f33" menuActiveBefore: "#e85f33"
}, },
yellow: { yellow: {
color: "#fadb14", vxeColor: "#fadb14",
subMenuActiveText: "#d25f00", subMenuActiveText: "#d25f00",
menuBg: "#2b2503", menuBg: "#2b2503",
menuHover: "#f6da4d", menuHover: "#f6da4d",
@@ -65,7 +79,7 @@ const themeColors = {
menuActiveBefore: "#f6da4d" menuActiveBefore: "#f6da4d"
}, },
mingQing: { mingQing: {
color: "#13c2c2", vxeColor: "#13c2c2",
subMenuActiveText: "#fff", subMenuActiveText: "#fff",
menuBg: "#032121", menuBg: "#032121",
menuHover: "#59bfc1", menuHover: "#59bfc1",
@@ -78,7 +92,7 @@ const themeColors = {
menuActiveBefore: "#59bfc1" menuActiveBefore: "#59bfc1"
}, },
auroraGreen: { auroraGreen: {
color: "#52c41a", vxeColor: "#52c41a",
subMenuActiveText: "#fff", subMenuActiveText: "#fff",
menuBg: "#0b1e15", menuBg: "#0b1e15",
menuHover: "#60ac80", menuHover: "#60ac80",
@@ -91,7 +105,7 @@ const themeColors = {
menuActiveBefore: "#60ac80" menuActiveBefore: "#60ac80"
}, },
pink: { pink: {
color: "#eb2f96", vxeColor: "#eb2f96",
subMenuActiveText: "#fff", subMenuActiveText: "#fff",
menuBg: "#28081a", menuBg: "#28081a",
menuHover: "#d84493", menuHover: "#d84493",
@@ -104,7 +118,7 @@ const themeColors = {
menuActiveBefore: "#d84493" menuActiveBefore: "#d84493"
}, },
saucePurple: { saucePurple: {
color: "#722ed1", vxeColor: "#722ed1",
subMenuActiveText: "#fff", subMenuActiveText: "#fff",
menuBg: "#130824", menuBg: "#130824",
menuHover: "#693ac9", menuHover: "#693ac9",
@@ -118,19 +132,28 @@ const themeColors = {
} }
}; };
type MultipleScopeVarsItem = { /**
scopeName: string; * @description 将预设主题色处理成主题插件所需格式
path: string; */
varsContent: string; export const genScssMultipleScopeVars = (): MultipleScopeVarsItem[] => {
};
export function genScssMultipleScopeVars(): MultipleScopeVarsItem[] {
const result = [] as MultipleScopeVarsItem[]; const result = [] as MultipleScopeVarsItem[];
Object.keys(themeColors).forEach(key => { Object.keys(themeColors).forEach(key => {
result.push({ result.push({
scopeName: `layout-theme-${key}`, scopeName: `layout-theme-${key}`,
varsContent: `$primary-color: ${themeColors[key].color} !default;$vxe-primary-color: $primary-color;$subMenuActiveText: ${themeColors[key].subMenuActiveText} !default;$menuBg: ${themeColors[key].menuBg} !default;$menuHover: ${themeColors[key].menuHover} !default;$subMenuBg: ${themeColors[key].subMenuBg} !default;$subMenuActiveBg: ${themeColors[key].subMenuActiveBg} !default;$navTextColor: ${themeColors[key].navTextColor} !default;$menuText: ${themeColors[key].menuText} !default;$sidebarLogo: ${themeColors[key].sidebarLogo} !default;$menuTitleHover: ${themeColors[key].menuTitleHover} !default;$menuActiveBefore: ${themeColors[key].menuActiveBefore} !default;` varsContent: `
$vxe-primary-color: ${themeColors[key].vxeColor} !default;
$subMenuActiveText: ${themeColors[key].subMenuActiveText} !default;
$menuBg: ${themeColors[key].menuBg} !default;
$menuHover: ${themeColors[key].menuHover} !default;
$subMenuBg: ${themeColors[key].subMenuBg} !default;
$subMenuActiveBg: ${themeColors[key].subMenuActiveBg} !default;
$navTextColor: ${themeColors[key].navTextColor} !default;
$menuText: ${themeColors[key].menuText} !default;
$sidebarLogo: ${themeColors[key].sidebarLogo} !default;
$menuTitleHover: ${themeColors[key].menuTitleHover} !default;
$menuActiveBefore: ${themeColors[key].menuActiveBefore} !default;
`
} as MultipleScopeVarsItem); } as MultipleScopeVarsItem);
}); });
return result; return result;
} };

View File

@@ -1,4 +1,3 @@
import { Component } from "vue";
export const routerArrays: Array<RouteConfigs> = [ export const routerArrays: Array<RouteConfigs> = [
{ {
path: "/welcome", path: "/welcome",
@@ -12,17 +11,17 @@ export const routerArrays: Array<RouteConfigs> = [
export type routeMetaType = { export type routeMetaType = {
title?: string; title?: string;
i18n?: boolean;
icon?: string; icon?: string;
showLink?: boolean; showLink?: boolean;
savedPosition?: boolean; savedPosition?: boolean;
authority?: Array<string>; auths?: Array<string>;
}; };
export type RouteConfigs = { export type RouteConfigs = {
path?: string; path?: string;
parentPath?: string; parentPath?: string;
query?: object; query?: object;
params?: object;
meta?: routeMetaType; meta?: routeMetaType;
children?: RouteConfigs[]; children?: RouteConfigs[];
name?: string; name?: string;
@@ -33,7 +32,7 @@ export type multiTagsType = {
}; };
export type tagsViewsType = { export type tagsViewsType = {
icon: Component; icon: string;
text: string; text: string;
divided: boolean; divided: boolean;
disabled: boolean; disabled: boolean;
@@ -44,7 +43,7 @@ export interface setType {
sidebar: { sidebar: {
opened: boolean; opened: boolean;
withoutAnimation: boolean; withoutAnimation: boolean;
isClickHamburger: boolean; isClickCollapse: boolean;
}; };
device: string; device: string;
fixedHeader: boolean; fixedHeader: boolean;
@@ -65,7 +64,6 @@ export type childrenType = {
meta?: { meta?: {
icon?: string; icon?: string;
title?: string; title?: string;
i18n?: boolean;
showParent?: boolean; showParent?: boolean;
extraIcon?: { extraIcon?: {
svg?: boolean; svg?: boolean;

View File

@@ -6,9 +6,13 @@ import { getServerConfig } from "./config";
import { createApp, Directive } from "vue"; import { createApp, Directive } from "vue";
import { useI18n } from "../src/plugins/i18n"; import { useI18n } from "../src/plugins/i18n";
import { MotionPlugin } from "@vueuse/motion"; import { MotionPlugin } from "@vueuse/motion";
import { injectResponsiveStorage } from "/@/utils/storage/responsive"; // import { useEcharts } from "/@/plugins/echarts";
// import { useTable } from "../src/plugins/vxe-table";
import { injectResponsiveStorage } from "/@/utils/responsive";
// import Table from "@pureadmin/table";
// import PureDescriptions from "@pureadmin/descriptions";
import "uno.css";
import "animate.css"; import "animate.css";
// 引入重置样式 // 引入重置样式
import "./style/reset.scss"; import "./style/reset.scss";
@@ -17,6 +21,7 @@ import "./style/index.scss";
import "element-plus/dist/index.css"; import "element-plus/dist/index.css";
import "@pureadmin/components/dist/index.css"; import "@pureadmin/components/dist/index.css";
import "@pureadmin/components/dist/theme.css"; import "@pureadmin/components/dist/theme.css";
import "@pureadmin/components/dist/dark.scss";
// 导入字体图标 // 导入字体图标
import "./assets/iconfont/iconfont.js"; import "./assets/iconfont/iconfont.js";
import "./assets/iconfont/iconfont.css"; import "./assets/iconfont/iconfont.css";
@@ -39,11 +44,19 @@ app.component("IconifyIconOffline", IconifyIconOffline);
app.component("IconifyIconOnline", IconifyIconOnline); app.component("IconifyIconOnline", IconifyIconOnline);
app.component("FontIcon", FontIcon); app.component("FontIcon", FontIcon);
// 全局注册按钮级别权限组件
import { Auth } from "/@/components/ReAuth";
app.component("Auth", Auth);
getServerConfig(app).then(async config => { getServerConfig(app).then(async config => {
app.use(router); app.use(router);
await router.isReady(); await router.isReady();
injectResponsiveStorage(app, config); injectResponsiveStorage(app, config);
setupStore(app); setupStore(app);
app.use(MotionPlugin).use(useI18n).use(ElementPlus); app.use(MotionPlugin).use(useI18n).use(ElementPlus);
// .use(useEcharts);
// .use(Table);
// .use(PureDescriptions);
// .use(useTable);
app.mount("#app"); app.mount("#app");
}); });

View File

@@ -1,6 +1,8 @@
import { createProdMockServer } from "vite-plugin-mock/es/createProdMockServer"; import { createProdMockServer } from "vite-plugin-mock/es/createProdMockServer";
const modules = import.meta.globEager("../mock/*.ts"); const modules: Record<string, any> = import.meta.glob("../mock/*.ts", {
eager: true
});
const mockModules = []; const mockModules = [];
Object.keys(modules).forEach(key => { Object.keys(modules).forEach(key => {

View File

@@ -0,0 +1,41 @@
import type { App } from "vue";
import * as echarts from "echarts/core";
import { SVGRenderer } from "echarts/renderers";
import { PieChart, BarChart, LineChart } from "echarts/charts";
import {
GridComponent,
TitleComponent,
LegendComponent,
GraphicComponent,
ToolboxComponent,
TooltipComponent,
DataZoomComponent,
VisualMapComponent
} from "echarts/components";
const { use } = echarts;
use([
PieChart,
BarChart,
LineChart,
SVGRenderer,
GridComponent,
TitleComponent,
LegendComponent,
GraphicComponent,
ToolboxComponent,
TooltipComponent,
DataZoomComponent,
VisualMapComponent
]);
/**
* @description 按需引入echarts
* @see {@link https://echarts.apache.org/handbook/zh/basics/import#%E6%8C%89%E9%9C%80%E5%BC%95%E5%85%A5-echarts-%E5%9B%BE%E8%A1%A8%E5%92%8C%E7%BB%84%E4%BB%B6}
*/
export function useEcharts(app: App) {
app.config.globalProperties.$echarts = echarts;
}
export default echarts;

View File

@@ -1,6 +1,8 @@
import { App, Component } from "vue"; import { App, Component } from "vue";
import { import {
ElTag, ElTag,
ElAffix,
ElSkeleton,
ElBreadcrumb, ElBreadcrumb,
ElBreadcrumbItem, ElBreadcrumbItem,
ElScrollbar, ElScrollbar,
@@ -8,21 +10,30 @@ import {
ElButton, ElButton,
ElCol, ElCol,
ElRow, ElRow,
ElSpace,
ElDivider, ElDivider,
ElCard,
ElDropdown, ElDropdown,
ElDialog,
ElMenu, ElMenu,
ElMenuItem, ElMenuItem,
ElDropdownItem, ElDropdownItem,
ElDropdownMenu, ElDropdownMenu,
ElIcon, ElIcon,
ElInput, ElInput,
ElForm,
ElFormItem,
ElPopover, ElPopover,
ElPopper, ElPopper,
ElTooltip, ElTooltip,
ElDrawer, ElDrawer,
ElPagination,
ElAlert,
ElRadio, ElRadio,
ElRadioButton, ElRadioButton,
ElRadioGroup, ElRadioGroup,
ElDescriptions,
ElDescriptionsItem,
ElBacktop, ElBacktop,
ElSwitch, ElSwitch,
ElBadge, ElBadge,
@@ -32,8 +43,22 @@ import {
ElEmpty, ElEmpty,
ElCollapse, ElCollapse,
ElCollapseItem, ElCollapseItem,
ElDialog, ElTable,
ElCard, ElTableColumn,
ElLink,
ElColorPicker,
ElSelect,
ElOption,
ElTimeline,
ElTimelineItem,
ElResult,
ElSteps,
ElStep,
ElTree,
ElTreeV2,
ElPopconfirm,
ElCheckbox,
ElCheckboxGroup,
// 指令 // 指令
ElLoading, ElLoading,
ElInfiniteScroll ElInfiniteScroll
@@ -44,6 +69,8 @@ const plugins = [ElLoading, ElInfiniteScroll];
const components = [ const components = [
ElTag, ElTag,
ElAffix,
ElSkeleton,
ElBreadcrumb, ElBreadcrumb,
ElBreadcrumbItem, ElBreadcrumbItem,
ElScrollbar, ElScrollbar,
@@ -51,21 +78,30 @@ const components = [
ElButton, ElButton,
ElCol, ElCol,
ElRow, ElRow,
ElSpace,
ElDivider, ElDivider,
ElCard,
ElDropdown, ElDropdown,
ElDialog,
ElMenu, ElMenu,
ElMenuItem, ElMenuItem,
ElDropdownItem, ElDropdownItem,
ElDropdownMenu, ElDropdownMenu,
ElIcon, ElIcon,
ElInput, ElInput,
ElForm,
ElFormItem,
ElPopover, ElPopover,
ElPopper, ElPopper,
ElTooltip, ElTooltip,
ElDrawer, ElDrawer,
ElPagination,
ElAlert,
ElRadio, ElRadio,
ElRadioButton, ElRadioButton,
ElRadioGroup, ElRadioGroup,
ElDescriptions,
ElDescriptionsItem,
ElBacktop, ElBacktop,
ElSwitch, ElSwitch,
ElBadge, ElBadge,
@@ -75,8 +111,22 @@ const components = [
ElEmpty, ElEmpty,
ElCollapse, ElCollapse,
ElCollapseItem, ElCollapseItem,
ElDialog, ElTree,
ElCard ElTreeV2,
ElPopconfirm,
ElCheckbox,
ElCheckboxGroup,
ElTable,
ElTableColumn,
ElLink,
ElColorPicker,
ElSelect,
ElOption,
ElTimeline,
ElTimelineItem,
ElResult,
ElSteps,
ElStep
]; ];
export function useElementPlus(app: App) { export function useElementPlus(app: App) {

View File

@@ -1,6 +1,7 @@
// 多组件库的国际化和本地项目国际化兼容 // 多组件库的国际化和本地项目国际化兼容
import { App, WritableComputedRef } from "vue"; import { App, WritableComputedRef } from "vue";
import { storageLocal } from "/@/utils/storage"; import type { StorageConfigs } from "/#/index";
import { storageLocal } from "@pureadmin/utils";
import { type I18n, createI18n } from "vue-i18n"; import { type I18n, createI18n } from "vue-i18n";
// element-plus国际化 // element-plus国际化
@@ -9,12 +10,12 @@ import zhLocale from "element-plus/lib/locale/lang/zh-cn";
function siphonI18n(prefix = "zh-CN") { function siphonI18n(prefix = "zh-CN") {
return Object.fromEntries( return Object.fromEntries(
Object.entries(import.meta.globEager("../../locales/*.y(a)?ml")).map( Object.entries(
([key, value]) => { import.meta.glob("../../locales/*.y(a)?ml", { eager: true })
const matched = key.match(/([A-Za-z0-9-_]+)\./i)[1]; ).map(([key, value]: any) => {
return [matched, value.default]; const matched = key.match(/([A-Za-z0-9-_]+)\./i)[1];
} return [matched, value.default];
) })
)[prefix]; )[prefix];
} }
@@ -57,12 +58,13 @@ export function transformI18n(message: any = "") {
} }
} }
// 此函数只是配合i18n Ally插件来进行国际化智能提示并无实际意义只对提示起作用如果不需要国际化可删除 /** 此函数只是配合i18n Ally插件来进行国际化智能提示并无实际意义只对提示起作用如果不需要国际化可删除 */
export const $t = (key: string) => key; export const $t = (key: string) => key;
export const i18n: I18n = createI18n({ export const i18n: I18n = createI18n({
legacy: false, legacy: false,
locale: storageLocal.getItem("responsive-locale")?.locale ?? "zh", locale:
storageLocal.getItem<StorageConfigs>("responsive-locale")?.locale ?? "zh",
fallbackLocale: "en", fallbackLocale: "en",
messages: localesConfigs messages: localesConfigs
}); });

View File

@@ -0,0 +1,6 @@
@import "vxe-table/styles/variable.scss";
@import "vxe-table/styles/modules.scss";
i {
border-color: initial;
}

View File

@@ -0,0 +1,114 @@
import "xe-utils";
import "./index.scss";
import XEUtils from "xe-utils";
import { App, unref } from "vue";
import { i18n } from "/@/plugins/i18n";
import "font-awesome/css/font-awesome.min.css";
import zh from "vxe-table/lib/locale/lang/zh-CN";
import en from "vxe-table/lib/locale/lang/en-US";
import {
// 核心
VXETable,
// 表格功能
Icon,
Filter,
Edit,
Menu,
Export,
Keyboard,
Validator,
// 可选组件
Column,
Colgroup,
Grid,
Tooltip,
Toolbar,
Pager,
Form,
FormItem,
FormGather,
Checkbox,
CheckboxGroup,
Radio,
RadioGroup,
RadioButton,
Switch,
Input,
Select,
Optgroup,
Option,
Textarea,
Button,
Modal,
List,
Pulldown,
// 表格
Table
} from "vxe-table";
// 全局默认参数
VXETable.setup({
size: "medium",
version: 0,
zIndex: 1002,
table: {
// 自动监听父元素的变化去重新计算表格
autoResize: true,
// 鼠标移到行是否要高亮显示
highlightHoverRow: true
},
input: {
clearable: true
},
i18n: (key, args) => {
return unref(i18n.global.locale) === "zh"
? XEUtils.toFormatString(XEUtils.get(zh, key), args)
: XEUtils.toFormatString(XEUtils.get(en, key), args);
},
translate(key) {
const NAMESPACED = ["el.", "buttons."];
if (key && NAMESPACED.findIndex(v => key.includes(v)) !== -1) {
return i18n.global.t.call(i18n.global.locale, key);
}
return key;
}
});
export function useTable(app: App) {
app
.use(Icon)
.use(Filter)
.use(Edit)
.use(Menu)
.use(Export)
.use(Keyboard)
.use(Validator)
// 可选组件
.use(Column)
.use(Colgroup)
.use(Grid)
.use(Tooltip)
.use(Toolbar)
.use(Pager)
.use(Form)
.use(FormItem)
.use(FormGather)
.use(Checkbox)
.use(CheckboxGroup)
.use(Radio)
.use(RadioGroup)
.use(RadioButton)
.use(Switch)
.use(Input)
.use(Select)
.use(Optgroup)
.use(Option)
.use(Textarea)
.use(Button)
.use(Modal)
.use(List)
.use(Pulldown)
// 安装表格
.use(Table);
}

View File

@@ -1,59 +1,60 @@
import { isUrl } from "/@/utils/is";
import { getConfig } from "/@/config"; import { getConfig } from "/@/config";
import { toRouteType } from "./types"; import { toRouteType } from "./types";
import { openLink } from "/@/utils/link";
import NProgress from "/@/utils/progress"; import NProgress from "/@/utils/progress";
import { findIndex } from "lodash-unified"; import { findIndex } from "lodash-unified";
import { transformI18n } from "/@/plugins/i18n"; import { transformI18n } from "/@/plugins/i18n";
import { storageSession } from "/@/utils/storage"; import { sessionKey, type DataInfo } from "/@/utils/auth";
import { buildHierarchyTree } from "/@/utils/tree";
import { useMultiTagsStoreHook } from "/@/store/modules/multiTags"; import { useMultiTagsStoreHook } from "/@/store/modules/multiTags";
import { usePermissionStoreHook } from "/@/store/modules/permission"; import { usePermissionStoreHook } from "/@/store/modules/permission";
import { import {
Router, Router,
RouteMeta,
createRouter, createRouter,
RouteRecordRaw, RouteRecordRaw,
RouteComponent, RouteComponent
RouteRecordName
} from "vue-router"; } from "vue-router";
import { import {
ascending, ascending,
initRouter, initRouter,
isOneOfArray,
getHistoryMode, getHistoryMode,
getParentPaths,
findRouteByPath, findRouteByPath,
handleAliveRoute, handleAliveRoute,
formatTwoStageRoutes, formatTwoStageRoutes,
formatFlatteningRoutes formatFlatteningRoutes
} from "./utils"; } from "./utils";
import {
buildHierarchyTree,
openLink,
isUrl,
storageSession
} from "@pureadmin/utils";
import homeRouter from "./modules/home"; import homeRouter from "./modules/home";
import errorRouter from "./modules/error"; import errorRouter from "./modules/error";
import remainingRouter from "./modules/remaining"; import remainingRouter from "./modules/remaining";
// 原始静态路由(未做任何处理) /** 原始静态路由(未做任何处理) */
const routes = [homeRouter, errorRouter]; const routes = [homeRouter, errorRouter];
// 导出处理后的静态路由(三级及以上的路由全部拍成二级) /** 导出处理后的静态路由(三级及以上的路由全部拍成二级) */
export const constantRoutes: Array<RouteRecordRaw> = formatTwoStageRoutes( export const constantRoutes: Array<RouteRecordRaw> = formatTwoStageRoutes(
formatFlatteningRoutes(buildHierarchyTree(ascending(routes))) formatFlatteningRoutes(buildHierarchyTree(ascending(routes)))
); );
// 用于渲染菜单,保持原始层级 /** 用于渲染菜单,保持原始层级 */
export const constantMenus: Array<RouteComponent> = ascending(routes).concat( export const constantMenus: Array<RouteComponent> = ascending(routes).concat(
...remainingRouter ...remainingRouter
); );
// 不参与菜单的路由 /** 不参与菜单的路由 */
export const remainingPaths = Object.keys(remainingRouter).map(v => { export const remainingPaths = Object.keys(remainingRouter).map(v => {
return remainingRouter[v].path; return remainingRouter[v].path;
}); });
// 创建路由实例 /** 创建路由实例 */
export const router: Router = createRouter({ export const router: Router = createRouter({
history: getHistoryMode(), history: getHistoryMode(),
routes: constantRoutes.concat(...remainingRouter), routes: constantRoutes.concat(...(remainingRouter as any)),
strict: true, strict: true,
scrollBehavior(to, from, savedPosition) { scrollBehavior(to, from, savedPosition) {
return new Promise(resolve => { return new Promise(resolve => {
@@ -70,7 +71,21 @@ export const router: Router = createRouter({
} }
}); });
// 路由白名单 /** 重置路由 */
export function resetRouter() {
router.getRoutes().forEach(route => {
const { name, meta } = route;
if (name && router.hasRoute(name) && meta?.backstage) {
router.removeRoute(name);
router.options.routes = formatTwoStageRoutes(
formatFlatteningRoutes(buildHierarchyTree(ascending(routes)))
);
}
});
usePermissionStoreHook().clearAllCachePage();
}
/** 路由白名单 */
const whiteList = ["/login"]; const whiteList = ["/login"];
router.beforeEach((to: toRouteType, _from, next) => { router.beforeEach((to: toRouteType, _from, next) => {
@@ -78,14 +93,14 @@ router.beforeEach((to: toRouteType, _from, next) => {
const newMatched = to.matched; const newMatched = to.matched;
handleAliveRoute(newMatched, "add"); handleAliveRoute(newMatched, "add");
// 页面整体刷新和点击标签页刷新 // 页面整体刷新和点击标签页刷新
if (_from.name === undefined || _from.name === "redirect") { if (_from.name === undefined || _from.name === "Redirect") {
handleAliveRoute(newMatched); handleAliveRoute(newMatched);
} }
} }
const name = storageSession.getItem("info"); const userInfo = storageSession.getItem<DataInfo<number>>(sessionKey);
NProgress.start(); NProgress.start();
const externalLink = isUrl(to?.name); const externalLink = isUrl(to?.name as string);
if (!externalLink) if (!externalLink) {
to.matched.some(item => { to.matched.some(item => {
if (!item.meta.title) return ""; if (!item.meta.title) return "";
const Title = getConfig().Title; const Title = getConfig().Title;
@@ -93,83 +108,44 @@ router.beforeEach((to: toRouteType, _from, next) => {
document.title = `${transformI18n(item.meta.title)} | ${Title}`; document.title = `${transformI18n(item.meta.title)} | ${Title}`;
else document.title = transformI18n(item.meta.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) { if (_from?.name) {
// name为超链接 // name为超链接
if (externalLink) { if (externalLink) {
openLink(to?.name); openLink(to?.name as string);
NProgress.done(); NProgress.done();
} else { } else {
next(); next();
} }
} else { } else {
// 刷新 // 刷新
if (usePermissionStoreHook().wholeMenus.length === 0) if (
initRouter(name.username).then((router: Router) => { usePermissionStoreHook().wholeMenus.length === 0 &&
to.path !== "/login"
)
initRouter().then((router: Router) => {
if (!useMultiTagsStoreHook().getMultiTagsCache) { if (!useMultiTagsStoreHook().getMultiTagsCache) {
const handTag = ( const { path } = to;
path: string, const index = findIndex(remainingRouter, v => {
parentPath: string, return v.path == path;
name: RouteRecordName, });
meta: RouteMeta const routes: any =
): void => { index === -1
? router.options.routes[0].children
: router.options.routes;
const route = findRouteByPath(path, routes);
// query、params模式路由传参数的标签页不在此处处理
if (route && route.meta?.title) {
useMultiTagsStoreHook().handleTags("push", { useMultiTagsStoreHook().handleTags("push", {
path, path: route.path,
parentPath, name: route.name,
name, meta: route.meta
meta
}); });
};
// 未开启标签页缓存,刷新页面重定向到顶级路由(参考标签页操作例子,只针对静态路由)
if (to.meta?.refreshRedirect) {
const routes = router.options.routes;
const { refreshRedirect } = to.meta;
const { name, meta } = findRouteByPath(refreshRedirect, routes);
handTag(
refreshRedirect,
getParentPaths(refreshRedirect, routes)[1],
name,
meta
);
return router.push(refreshRedirect);
} else {
const { path } = to;
const index = findIndex(remainingRouter, v => {
return v.path == path;
});
const routes =
index === -1
? router.options.routes[0].children
: router.options.routes;
const route = findRouteByPath(path, routes);
const routePartent = getParentPaths(path, routes);
// 未开启标签页缓存,刷新页面重定向到顶级路由(参考标签页操作例子,只针对动态路由)
if (
path !== routes[0].path &&
route?.meta?.rank !== 0 &&
routePartent.length === 0
) {
if (!route?.meta?.refreshRedirect) return;
const { name, meta } = findRouteByPath(
route.meta.refreshRedirect,
routes
);
handTag(
route.meta?.refreshRedirect,
getParentPaths(route.meta?.refreshRedirect, routes)[0],
name,
meta
);
return router.push(route.meta?.refreshRedirect);
} else {
handTag(
route.path,
routePartent[routePartent.length - 1],
route.name,
route.meta
);
return router.push(path);
}
} }
} }
router.push(to.fullPath); router.push(to.fullPath);

View File

@@ -1,13 +1,12 @@
import { $t } from "/@/plugins/i18n"; import { $t } from "/@/plugins/i18n";
const Layout = () => import("/@/layout/index.vue"); import type { RouteConfigsTable } from "/#/index";
const errorRouter = { const errorRouter: RouteConfigsTable = {
path: "/error", path: "/error",
component: Layout,
redirect: "/error/403", redirect: "/error/403",
meta: { meta: {
icon: "information-line", icon: "information-line",
title: $t("menus.hserror"), title: $t("menus.hsabnormal"),
rank: 9 rank: 9
}, },
children: [ children: [

View File

@@ -1,9 +1,10 @@
import { $t } from "/@/plugins/i18n"; import { $t } from "/@/plugins/i18n";
import type { RouteConfigsTable } from "/#/index";
const Layout = () => import("/@/layout/index.vue"); const Layout = () => import("/@/layout/index.vue");
const homeRouter = { const homeRouter: RouteConfigsTable = {
path: "/", path: "/",
name: "home", name: "Home",
component: Layout, component: Layout,
redirect: "/welcome", redirect: "/welcome",
meta: { meta: {
@@ -14,8 +15,8 @@ const homeRouter = {
children: [ children: [
{ {
path: "/welcome", path: "/welcome",
name: "welcome", name: "Welcome",
component: () => import("/@/views/welcome.vue"), component: () => import("/@/views/welcome/index.vue"),
meta: { meta: {
title: $t("menus.hshome") title: $t("menus.hshome")
} }

View File

@@ -1,10 +1,11 @@
import { $t } from "/@/plugins/i18n"; import { $t } from "/@/plugins/i18n";
import type { RouteConfigsTable } from "/#/index";
const Layout = () => import("/@/layout/index.vue"); const Layout = () => import("/@/layout/index.vue");
const remainingRouter = [ const remainingRouter: Array<RouteConfigsTable> = [
{ {
path: "/login", path: "/login",
name: "login", name: "Login",
component: () => import("/@/views/login/index.vue"), component: () => import("/@/views/login/index.vue"),
meta: { meta: {
title: $t("menus.hslogin"), title: $t("menus.hslogin"),
@@ -24,7 +25,7 @@ const remainingRouter = [
children: [ children: [
{ {
path: "/redirect/:path(.*)", path: "/redirect/:path(.*)",
name: "redirect", name: "Redirect",
component: () => import("/@/layout/redirect.vue") component: () => import("/@/layout/redirect.vue")
} }
] ]

Some files were not shown because too many files have changed in this diff Show More