Merge pull request #189 from betaxab/pr-standardize-line-endings

misc: Unify line endings to Unix LF format
This commit is contained in:
莫名
2026-05-06 13:39:05 +08:00
committed by GitHub
105 changed files with 11052 additions and 11052 deletions
+36 -36
View File
@@ -1,37 +1,37 @@
<!-- By Sam Herbert (@sherb), for everyone. More @ http://goo.gl/7AJzbL -->
<svg width="44" height="44" viewBox="0 0 44 44" xmlns="http://www.w3.org/2000/svg" stroke="#fff">
<g fill="none" fill-rule="evenodd" stroke-width="2">
<circle cx="22" cy="22" r="1">
<animate attributeName="r"
begin="0s" dur="1.8s"
values="1; 20"
calcMode="spline"
keyTimes="0; 1"
keySplines="0.165, 0.84, 0.44, 1"
repeatCount="indefinite" />
<animate attributeName="stroke-opacity"
begin="0s" dur="1.8s"
values="1; 0"
calcMode="spline"
keyTimes="0; 1"
keySplines="0.3, 0.61, 0.355, 1"
repeatCount="indefinite" />
</circle>
<circle cx="22" cy="22" r="1">
<animate attributeName="r"
begin="-0.9s" dur="1.8s"
values="1; 20"
calcMode="spline"
keyTimes="0; 1"
keySplines="0.165, 0.84, 0.44, 1"
repeatCount="indefinite" />
<animate attributeName="stroke-opacity"
begin="-0.9s" dur="1.8s"
values="1; 0"
calcMode="spline"
keyTimes="0; 1"
keySplines="0.3, 0.61, 0.355, 1"
repeatCount="indefinite" />
</circle>
</g>
<!-- By Sam Herbert (@sherb), for everyone. More @ http://goo.gl/7AJzbL -->
<svg width="44" height="44" viewBox="0 0 44 44" xmlns="http://www.w3.org/2000/svg" stroke="#fff">
<g fill="none" fill-rule="evenodd" stroke-width="2">
<circle cx="22" cy="22" r="1">
<animate attributeName="r"
begin="0s" dur="1.8s"
values="1; 20"
calcMode="spline"
keyTimes="0; 1"
keySplines="0.165, 0.84, 0.44, 1"
repeatCount="indefinite" />
<animate attributeName="stroke-opacity"
begin="0s" dur="1.8s"
values="1; 0"
calcMode="spline"
keyTimes="0; 1"
keySplines="0.3, 0.61, 0.355, 1"
repeatCount="indefinite" />
</circle>
<circle cx="22" cy="22" r="1">
<animate attributeName="r"
begin="-0.9s" dur="1.8s"
values="1; 20"
calcMode="spline"
keyTimes="0; 1"
keySplines="0.165, 0.84, 0.44, 1"
repeatCount="indefinite" />
<animate attributeName="stroke-opacity"
begin="-0.9s" dur="1.8s"
values="1; 0"
calcMode="spline"
keyTimes="0; 1"
keySplines="0.3, 0.61, 0.355, 1"
repeatCount="indefinite" />
</circle>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

+15 -15
View File
@@ -1,15 +1,15 @@
# @see: http://editorconfig.org
root = true
[*] # 表示所有文件适用
charset = utf-8 # 设置文件字符集为 utf-8
indent_style = space # 缩进风格(tab | space)
indent_size = 2 # 缩进大小
max_line_length = 130 # 最大行长度
end_of_line = crlf # 控制换行类型(lf | cr | crlf)
insert_final_newline = true # 始终在文件末尾插入一个新行
[*.md] # 表示仅对 md 文件适用以下规则
max_line_length = off # 关闭最大行长度限制
trim_trailing_whitespace = false # 关闭末尾空格修剪
# @see: http://editorconfig.org
root = true
[*] # 表示所有文件适用
charset = utf-8 # 设置文件字符集为 utf-8
indent_style = space # 缩进风格(tab | space)
indent_size = 2 # 缩进大小
max_line_length = 130 # 最大行长度
end_of_line = crlf # 控制换行类型(lf | cr | crlf)
insert_final_newline = true # 始终在文件末尾插入一个新行
[*.md] # 表示仅对 md 文件适用以下规则
max_line_length = off # 关闭最大行长度限制
trim_trailing_whitespace = false # 关闭末尾空格修剪
+14 -14
View File
@@ -1,14 +1,14 @@
# 生产环境优先级
# development & production & test > .env
# title
VITE_GLOB_APP_TITLE = 'BEpusdt'
# 静态资源url
VITE_IMG_BASE_URL = 'https://my-image-cdn.com'
# 本地mock数据 true开启 false关闭
VITE_APP_OPEN_MOCK = false
# 资源公共路径
VITE_PUBLIC_PATH = '/secure/'
# 生产环境优先级
# development & production & test > .env
# title
VITE_GLOB_APP_TITLE = 'BEpusdt'
# 静态资源url
VITE_IMG_BASE_URL = 'https://my-image-cdn.com'
# 本地mock数据 true开启 false关闭
VITE_APP_OPEN_MOCK = false
# 资源公共路径
VITE_PUBLIC_PATH = '/secure/'
+12 -12
View File
@@ -1,12 +1,12 @@
# 开发环境
VITE_USER_NODE_ENV = development
# 路由模式 hash | history
VITE_ROUTER_MODE = hash
# 打包路径 开发环境地址前缀 (一般 '/' 或 './' 都可以,如果开发环境 '/' 打包预览白屏,请使用 './')
# 默认情况下,vite 会假设你的应用是被部署在一个域名的根路径上,所以这里 VITE_PUBLIC_PATH 为 '/'
VITE_PUBLIC_PATH = './'
# 请求路径 管理系统/开发环境
VITE_APP_BASE_URL = 'http://127.0.0.1:8080'
# 开发环境
VITE_USER_NODE_ENV = development
# 路由模式 hash | history
VITE_ROUTER_MODE = hash
# 打包路径 开发环境地址前缀 (一般 '/' 或 './' 都可以,如果开发环境 '/' 打包预览白屏,请使用 './')
# 默认情况下,vite 会假设你的应用是被部署在一个域名的根路径上,所以这里 VITE_PUBLIC_PATH 为 '/'
VITE_PUBLIC_PATH = './'
# 请求路径 管理系统/开发环境
VITE_APP_BASE_URL = 'http://127.0.0.1:8080'
+10 -10
View File
@@ -1,11 +1,11 @@
# 开发环境
VITE_USER_NODE_ENV = test
# 路由模式 hash | history
VITE_ROUTER_MODE = hash
# 开发环境地址前缀 (一般 '/' 或 './' 都可以)
VITE_PUBLIC_PATH = '/test'
# 请求路径 管理系统/开发环境
# 开发环境
VITE_USER_NODE_ENV = test
# 路由模式 hash | history
VITE_ROUTER_MODE = hash
# 开发环境地址前缀 (一般 '/' 或 './' 都可以)
VITE_PUBLIC_PATH = '/test'
# 请求路径 管理系统/开发环境
VITE_APP_BASE_URL = '/'
+27 -27
View File
@@ -1,27 +1,27 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist.zip
dist.7z
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
!.vscode/settings.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist.zip
dist.7z
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
!.vscode/settings.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+1 -1
View File
@@ -1 +1 @@
npx --no-install commitlint --edit "$1"
npx --no-install commitlint --edit "$1"
+1 -1
View File
@@ -1 +1 @@
npm run lint:lint-staged
npm run lint:lint-staged
+41 -41
View File
@@ -1,41 +1,41 @@
// @see: https://www.prettier.cn
module.exports = {
// 指定最大换行长度
printWidth: 130,
// 缩进制表符宽度 | 空格数
tabWidth: 2,
// 使用制表符而不是空格缩进行 (true:制表符,false:空格)
useTabs: false,
// 结尾不用分号 (true:有,false:没有)
semi: true,
// 使用单引号 (true:单引号,false:双引号)
singleQuote: false,
// 在对象字面量中决定是否将属性名用引号括起来 可选值 "<as-needed|consistent|preserve>"
quoteProps: 'as-needed',
// 在JSX中使用单引号而不是双引号 (true:单引号,false:双引号)
jsxSingleQuote: false,
// 多行时尽可能打印尾随逗号 可选值"<none|es5|all>"
trailingComma: 'none',
// 在对象,数组括号与文字之间加空格 "{ foo: bar }" (true:有,false:没有)
bracketSpacing: true,
// 将 > 多行元素放在最后一行的末尾,而不是单独放在下一行 (true:放末尾,false:单独一行)
bracketSameLine: false,
// (x) => {} 箭头函数参数只有一个时是否要有小括号 (avoid:省略括号,always:不省略括号)
arrowParens: 'avoid',
// 指定要使用的解析器,不需要写文件开头的 @prettier
requirePragma: false,
// 可以在文件顶部插入一个特殊标记,指定该文件已使用 Prettier 格式化
insertPragma: false,
// 用于控制文本是否应该被换行以及如何进行换行
proseWrap: 'preserve',
// 在html中空格是否是敏感的 "css" - 遵守 CSS 显示属性的默认值, "strict" - 空格被认为是敏感的 ,"ignore" - 空格被认为是不敏感的
htmlWhitespaceSensitivity: 'css',
// 控制在 Vue 单文件组件中 <script> 和 <style> 标签内的代码缩进方式
vueIndentScriptAndStyle: false,
// 换行符使用 lf 结尾是 可选值 "<auto|lf|crlf|cr>"
endOfLine: 'auto',
// 这两个选项可用于格式化以给定字符偏移量(分别包括和不包括)开始和结束的代码 (rangeStart:开始,rangeEnd:结束)
rangeStart: 0,
rangeEnd: Infinity
};
// @see: https://www.prettier.cn
module.exports = {
// 指定最大换行长度
printWidth: 130,
// 缩进制表符宽度 | 空格数
tabWidth: 2,
// 使用制表符而不是空格缩进行 (true:制表符,false:空格)
useTabs: false,
// 结尾不用分号 (true:有,false:没有)
semi: true,
// 使用单引号 (true:单引号,false:双引号)
singleQuote: false,
// 在对象字面量中决定是否将属性名用引号括起来 可选值 "<as-needed|consistent|preserve>"
quoteProps: 'as-needed',
// 在JSX中使用单引号而不是双引号 (true:单引号,false:双引号)
jsxSingleQuote: false,
// 多行时尽可能打印尾随逗号 可选值"<none|es5|all>"
trailingComma: 'none',
// 在对象,数组括号与文字之间加空格 "{ foo: bar }" (true:有,false:没有)
bracketSpacing: true,
// 将 > 多行元素放在最后一行的末尾,而不是单独放在下一行 (true:放末尾,false:单独一行)
bracketSameLine: false,
// (x) => {} 箭头函数参数只有一个时是否要有小括号 (avoid:省略括号,always:不省略括号)
arrowParens: 'avoid',
// 指定要使用的解析器,不需要写文件开头的 @prettier
requirePragma: false,
// 可以在文件顶部插入一个特殊标记,指定该文件已使用 Prettier 格式化
insertPragma: false,
// 用于控制文本是否应该被换行以及如何进行换行
proseWrap: 'preserve',
// 在html中空格是否是敏感的 "css" - 遵守 CSS 显示属性的默认值, "strict" - 空格被认为是敏感的 ,"ignore" - 空格被认为是不敏感的
htmlWhitespaceSensitivity: 'css',
// 控制在 Vue 单文件组件中 <script> 和 <style> 标签内的代码缩进方式
vueIndentScriptAndStyle: false,
// 换行符使用 lf 结尾是 可选值 "<auto|lf|crlf|cr>"
endOfLine: 'auto',
// 这两个选项可用于格式化以给定字符偏移量(分别包括和不包括)开始和结束的代码 (rangeStart:开始,rangeEnd:结束)
rangeStart: 0,
rangeEnd: Infinity
};
+49 -49
View File
@@ -1,49 +1,49 @@
// @see: https://stylelint.io
module.exports = {
root: true,
// 继承某些已有的规则
extends: [
"stylelint-config-standard", // 配置 stylelint 拓展插件
"stylelint-config-html/vue", // 配置 vue 中 template 样式格式化
"stylelint-config-standard-scss", // 配置 stylelint scss 插件
"stylelint-config-recommended-vue/scss", // 配置 vue 中 scss 样式格式化
"stylelint-config-recess-order" // 配置 stylelint css 属性书写顺序插件,
],
overrides: [
// SCSS 文件解析器
{
files: ["**/*.scss"],
customSyntax: "postcss-scss"
},
// 扫描 .vue/html 文件中的 <style> 标签内的样式
{
files: ["**/*.{vue,html}"],
customSyntax: "postcss-html"
}
],
rules: {
"declaration-property-value-no-unknown": null, // 关闭属性值校验
"scss/dollar-variable-pattern": /.*/, // 允许任意变量名格式
"scss/at-rule-no-unknown": true, // 启用 SCSS 的 @规则校验
"scss/no-global-function-names": null, // 允许原生 CSS 函数名
"function-url-quotes": "always", // URL 的引号 "always(必须加上引号)"|"never(没有引号)"
"color-hex-length": "long", // 指定 16 进制颜色的简写或扩写 "short(16进制简写)"|"long(16进制扩写)"
"rule-empty-line-before": "never", // 要求或禁止在规则之前的空行 "always(规则之前必须始终有一个空行)"|"never(规则前绝不能有空行)"|"always-multi-line(多行规则之前必须始终有一个空行)"|"never-multi-line(多行规则之前绝不能有空行)"
"font-family-no-missing-generic-family-keyword": null, // 禁止在字体族名称列表中缺少通用字体族关键字
"scss/at-import-partial-extension": null, // 解决不能使用 @import 引入 scss 文件
"property-no-unknown": null, // 禁止未知的属性
"no-empty-source": null, // 禁止空源码
"selector-class-pattern": null, // 强制选择器类名的格式
"value-no-vendor-prefix": null, // 关闭 vendor-prefix (为了解决多行省略 -webkit-box)
"no-descending-specificity": null, // 不允许较低特异性的选择器出现在覆盖较高特异性的选择器
"value-keyword-case": null, // 解决在 scss 中使用 v-bind 大写单词报错
"selector-pseudo-class-no-unknown": [
true,
{
ignorePseudoClasses: ["global", "v-deep", "deep"]
}
]
},
ignoreFiles: ["**/*.js", "**/*.jsx", "**/*.tsx", "**/*.ts"]
};
// @see: https://stylelint.io
module.exports = {
root: true,
// 继承某些已有的规则
extends: [
"stylelint-config-standard", // 配置 stylelint 拓展插件
"stylelint-config-html/vue", // 配置 vue 中 template 样式格式化
"stylelint-config-standard-scss", // 配置 stylelint scss 插件
"stylelint-config-recommended-vue/scss", // 配置 vue 中 scss 样式格式化
"stylelint-config-recess-order" // 配置 stylelint css 属性书写顺序插件,
],
overrides: [
// SCSS 文件解析器
{
files: ["**/*.scss"],
customSyntax: "postcss-scss"
},
// 扫描 .vue/html 文件中的 <style> 标签内的样式
{
files: ["**/*.{vue,html}"],
customSyntax: "postcss-html"
}
],
rules: {
"declaration-property-value-no-unknown": null, // 关闭属性值校验
"scss/dollar-variable-pattern": /.*/, // 允许任意变量名格式
"scss/at-rule-no-unknown": true, // 启用 SCSS 的 @规则校验
"scss/no-global-function-names": null, // 允许原生 CSS 函数名
"function-url-quotes": "always", // URL 的引号 "always(必须加上引号)"|"never(没有引号)"
"color-hex-length": "long", // 指定 16 进制颜色的简写或扩写 "short(16进制简写)"|"long(16进制扩写)"
"rule-empty-line-before": "never", // 要求或禁止在规则之前的空行 "always(规则之前必须始终有一个空行)"|"never(规则前绝不能有空行)"|"always-multi-line(多行规则之前必须始终有一个空行)"|"never-multi-line(多行规则之前绝不能有空行)"
"font-family-no-missing-generic-family-keyword": null, // 禁止在字体族名称列表中缺少通用字体族关键字
"scss/at-import-partial-extension": null, // 解决不能使用 @import 引入 scss 文件
"property-no-unknown": null, // 禁止未知的属性
"no-empty-source": null, // 禁止空源码
"selector-class-pattern": null, // 强制选择器类名的格式
"value-no-vendor-prefix": null, // 关闭 vendor-prefix (为了解决多行省略 -webkit-box)
"no-descending-specificity": null, // 不允许较低特异性的选择器出现在覆盖较高特异性的选择器
"value-keyword-case": null, // 解决在 scss 中使用 v-bind 大写单词报错
"selector-pseudo-class-no-unknown": [
true,
{
ignorePseudoClasses: ["global", "v-deep", "deep"]
}
]
},
ignoreFiles: ["**/*.js", "**/*.jsx", "**/*.tsx", "**/*.ts"]
};
+44 -44
View File
@@ -1,44 +1,44 @@
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.stylelint": "explicit"
},
"stylelint.enable": true,
"stylelint.validate": ["css", "less", "postcss", "scss", "vue", "sass", "html"],
"files.eol": "\n",
"marscode.chatLanguage": "cn",
"[vue]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[scss]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[markdown]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[less]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"i18n-ally.localesPaths": [
"src/lang",
"src/views/i18n"
]
}
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.stylelint": "explicit"
},
"stylelint.enable": true,
"stylelint.validate": ["css", "less", "postcss", "scss", "vue", "sass", "html"],
"files.eol": "\n",
"marscode.chatLanguage": "cn",
"[vue]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[scss]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[markdown]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[less]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"i18n-ally.localesPaths": [
"src/lang",
"src/views/i18n"
]
}
+21 -21
View File
@@ -1,21 +1,21 @@
MIT License
Copyright (c) 2024 兔子先森Ace
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
MIT License
Copyright (c) 2024 兔子先森Ace
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+256 -256
View File
@@ -1,256 +1,256 @@
# SnowAdmin
<div>
<p>
<a href="https://github.com/WangFan-io/SnowAdmin" target="_blank">
<img src="https://img.shields.io/badge/License-MIT-%2343aefc" alt="License">
</a>
<a href="https://github.com/WangFan-io/SnowAdmin" target="_blank">
<img src="https://img.shields.io/badge/vue_.js-vue3_.x-%2300b42a" alt="Vue">
</a>
<a href="https://github.com/WangFan-io/SnowAdmin" target="_blank">
<img src="https://img.shields.io/badge/Vite-6x-%2311B337" alt="Vite">
</a>
<a href="https://github.com/WangFan-io/SnowAdmin" target="_blank">
<img alt="arco.design" src="https://img.shields.io/badge/arco.design-2.57.0-%23%2028%2C175%2C%2063">
</a>
</p>
</div>
### 介绍 📖
SnowAdmin 是一个清新优雅、高颜值且功能强大的后台管理模板,基于最新的前端技术栈,包括 Vue3, Vite6, TypeScript, Pinia。它内置了丰富的主题配置和组件,代码规范严谨,实现了自动化的文件路由系统。SnowAdmin 为您提供了一站式的后台管理解决方案,无需额外配置,开箱即用。同样是一个快速学习前沿技术的最佳实践。
### 版本 📦
**预览及文档**
项目预览地址:[SnowAdmin](http://115.190.79.132/#/login)
项目文档地址:[SnowAdmin-开发指南](http://115.190.79.132:81/)
**代码仓库**
| 平台 | 仓库地址 |
| ------ | ------------------------------------------------------ |
| GitHub | [Github 仓库](https://github.com/WangFan-io/SnowAdmin) |
| Gitee | [Gitee 仓库](https://gitee.com/wang_fan_w/SnowAdmin) |
> 完整版分支:main
>
> 极简版分支:main-thin
>
> ⚠️主要的维护在github上,提issue/pr请认准github主战场
>
> 大家也可以进wx群交流,二维码在介绍末尾
### 先行预览 🖼️
![登录页](https://ooo.0x0.ooo/2025/04/11/O0lhbG.png)
![首页](https://ooo.0x0.ooo/2025/04/11/O0lnVI.png)
![文件库](https://ooo.0x0.ooo/2025/04/11/O0l7qD.png)
![国际化](https://ooo.0x0.ooo/2025/04/11/O0lNAF.png)
![横向布局](https://ooo.0x0.ooo/2025/04/11/O0leQ6.png)
![混合布局](https://ooo.0x0.ooo/2025/04/11/O0lrCP.png)
![主题配置](https://ooo.0x0.ooo/2025/04/11/O0lKnb.png)
![黑暗模式-1](https://ooo.0x0.ooo/2025/04/11/O0lZ4l.png)
![黑暗模式-2](https://ooo.0x0.ooo/2025/04/11/O0lv6g.png)
![黑暗模式-3](https://ooo.0x0.ooo/2025/04/11/O0lgkB.png)
### 项目功能 🔨
- 清晰的项目架构:结构清晰,优雅易懂,代码全注释
- 前沿技术应用:采用 Vue3, Vite6, TypeScript等最新流行的技术栈
- 内置RBAC角色权限模型,实现路由、角色、按钮权限访问控制
- 使用 Pinia 替代 Vuex,轻量、简单、易用,集成 Pinia 持久化插件
- 支持 Arco-Design 组件大小切换、多主题布局、暗黑模式、i18n 国际化
- 使用 VueRouter 配置动态路由权限拦截、路由懒加载,支持页面按钮权限控制
- 使用 KeepAlive 对页面进行缓存,支持多级嵌套路由缓存
- 使用 Prettier 统一格式化代码,集成 ESLint、Stylelint 代码校验规范
- 使用 husky、lint-staged、commitlint等插件,规范提交信息
- 丰富的页面组件:内置多样页面和组件,包括 401、404、500 页面,以及布局组件、标签组件、主题配置组件等
### 环境准备 🏝️
确保你的环境满足以下要求(重要):
- **git**: 你需要 git 来克隆和管理项目版本。
- **NodeJS**: >=18.12.0,推荐 20.12.0 或更高。
- **pnpm**: >= 8.7.0,推荐最新版本。
### 安装使用步骤 📔
### 从 GitHub 获取代码 🔗
```bash
# 克隆代码
git clone https://github.com/WangFan-io/SnowAdmin.git
```
### 从 Gitee 获取代码 🔗
```bash
# 克隆代码
git clone https://gitee.com/wang_fan_w/SnowAdmin.git
```
### 安装依赖 📌
安装项目依赖
```bash
pnpm install
```
### 插件配置 🛠️
安装 Vue - Official,禁用 Vetur
- [Vue - Official](https://marketplace.visualstudio.com/items?itemName=Vue.volar) - Vue 服务插件
### 项目启动 🚀
```json
{
// 开发环境启动
"dev": "vite",
// 开发环境构建
"build:dev": "vue-tsc && vite build --mode development",
// 生产环境构建
"build:prod": "vue-tsc && vite build --mode production",
// 测试环境构建
"build:test": "vue-tsc && vite build --mode test",
// 预览环境启动
"preview": "vite preview"
}
```
### 文件资源目录 📚
```text
SnowAdmin
├─ .husky # husky 配置文件
├─ .vscode # VSCode 推荐配置
├─ build # vite项目配置目录
├─ public # 静态资源文件(该文件夹不会被打包)
├─ src
│ ├─ api # API 接口管理
│ ├─ assets # 静态资源文件
│ ├─ components # 全局组件
│ ├─ config # 全局配置项
│ ├─ directives # 全局自定义指令文件
│ ├─ globals # 全局函数
│ ├─ hooks # 常用 Hooks 封装
│ ├─ lang # 语言国际化 i18n
│ ├─ layout # 框架布局模块
│ ├─ mock # 本地数据mock
│ ├─ router # 路由管理
│ ├─ store # pinia store
│ ├─ style # 全局样式文件
│ ├─ typings # 全局 ts 声明
│ ├─ utils # 常用工具库
│ ├─ views # 项目所有页面
│ ├─ App.vue # 项目主组件
│ ├─ main.ts # 项目入口文件
│ └─ vite-env.d.ts # 指定 ts 识别 vue
├─ .editorconfig # 代码编辑器配置文件
├─ .env # 通用环境配置
├─ .env.development # 开发环境配置
├─ .env.production # 生产环境配置
├─ .env.test # 测试环境配置
├─ .eslintignore # 忽略 Eslint 校验
├─ .eslintrc.cjs # Eslint 校验配置文件
├─ .gitignore # 忽略 git 提交
├─ .prettierignore # 忽略 Prettier 格式化
├─ .prettierrc.cjs # Prettier 格式化配置
├─ .stylelintignore # 忽略 Stylelint 校验
├─ .stylelintrc.cjs # Stylelint 格式化配置
├─ commitlint.config.cjs # git 提交规范配置
├─ index.html # 入口 html
├─ LICENSE # 开源协议
├─ lint-staged.config.cjs # lint-staged 配置文件
├─ package-lock.json # 依赖包包版本锁
├─ package.json # 依赖包管理
├─ pnpm-lock.yaml # 依赖包包版本锁
├─ README.md # README 介绍
├─ tsconfig.json # typescript 全局配置
└─ vite.config.ts # vite 全局配置文件
```
### 浏览器支持 🌎
- 本地开发推荐使用 Chrome 最新版浏览器 [Download](https://www.google.com/intl/zh-CN/chrome/)。
- 生产环境支持现代浏览器,不再支持 IE 浏览器,更多浏览器可以查看 [Can I Use Es Module](https://caniuse.com/?search=ESModule)。
| ![IE](https://i.imgtg.com/2023/04/11/8z7ot.png) | ![Edge](https://i.imgtg.com/2023/04/11/8zr3p.png) | ![Firefox](https://i.imgtg.com/2023/04/11/8zKiU.png) | ![Chrome](https://i.imgtg.com/2023/04/11/8zNrx.png) | ![Safari](https://i.imgtg.com/2023/04/11/8zeGj.png) |
| :---------------------------------------------: | :-----------------------------------------------: | :--------------------------------------------------: | :-------------------------------------------------: | :-------------------------------------------------: |
| not support | last 2 versions | last 2 versions | last 2 versions | last 2 versions |
### 鸣谢列表 🧩
- [vue:https://v3.cn.vuejs.org/](https://v3.cn.vuejs.org/)
- [axios:https://github.com/axios/axios](https://github.com/axios/axios)
- [nprogress:https://github.com/rstacruz/nprogress](https://github.com/rstacruz/nprogress)
- [sortablejs:https://github.com/SortableJS/Sortabl](https://github.com/SortableJS/Sortable)
- [sass:https://github.com/sass/sass](https://github.com/sass/sass)
- [typescript:https://github.com/microsoft/TypeScript](https://github.com/microsoft/TypeScript)
- [vite:https://github.com/vitejs/vite](https://github.com/vitejs/vite)
- [wangeditor:https://github.com/wangeditor-team/wangEditor](https://github.com/wangeditor-team/wangEditor)
- [qrcodejs:https://github.com/davidshimjs/qrcodejs](https://github.com/davidshimjs/qrcodejs)
- [print-js:https://github.com/crabbly/Print.js](https://github.com/crabbly/Print.js)
- [eslint:https://github.com/eslint/eslint](https://github.com/eslint/eslint)
- [prettier:https://github.com/prettier/prettier](https://github.com/prettier/prettier)
- [arco.design:https://arco.design/](https://arco.design/)
- [pinyin-pro:https://github.com/zh-lx/pinyin-pro](https://github.com/zh-lx/pinyin-pro)
- [qrcode:https://www.npmjs.com/package/qrcode](https://www.npmjs.com/package/qrcode)
- [jsbarcode:https://github.com/lindell/JsBarcode/wiki/Options](https://github.com/lindell/JsBarcode/wiki/Options)
- [fingerprintjs2:https://www.npmjs.com/package/fingerprintjs2](https://www.npmjs.com/package/fingerprintjs2)
### 特别鸣谢 🎉
- [vue-next-admin:http://vuenextadmin.ccfast.cc/](http://vuenextadmin.ccfast.cc/)
- [Gi-admin:https://lin-97.github.io/gi-demo/](https://lin-97.github.io/gi-demo/#/home)
- [Geeker-Admin:https://admin.spicyboy.cn/](https://admin.spicyboy.cn/#/home/index)
感谢以上框架为本项目提供了帮助,项目中的很多设计思想值得参考和学习,再次感谢。
### 学习 & 交流 🏫
| SnowAdmin 交流群 |
| :---------------------------------------------------------------------------------------------------------: |
| ![微信图片_20250726141221](https://github.com/user-attachments/assets/8c1ebf3c-4630-487e-9a54-810fd4d6972c) |
使用过程中有各种问题也可以进群交流,欢迎大家积极参与
### 支持作者 🌟
如果觉得框架不错,或者已经在使用了,希望你可以去 [GitHub](https://github.com/WangFan-io/SnowAdmin) ⭐ Star,这将是对我极大的鼓励与支持。
### 免责条款 📫
您充分了解并同意,您必须为自己使用本服务及注册帐号下的一切行为负责,包括您所发表的任何内容以及由此产生的任何后果。您应对本服务中的内容自行加以判断,并自行承担因使用内容而引起的所有风险。
`SnowAdmin` 对网站上所显示的信息或资料的准确性、内容、完整性、合法性、可靠性、可操作性或可用性不承担任何责任。
`SnowAdmin` 二次开发使用者因为违法而触犯中华人民共和国法律的,一切后果自己负责,`SnowAdmin` 作者不承担任何责任。
本声明未涉及的问题参见国家有关法律法规,当本声明与国家法律法规冲突时,以国家法律法规为准。
### 学习 & 商用 🌈
`SnowAdmin` 是免费和开源的,可免费用于学习、商业使用 。
### 捐赠 💖
| 微信 | 支付宝 |
| :------------------------------------------------: | :--------------------------------------------------: |
| ![微信](https://ooo.0x0.ooo/2025/07/20/OYtFn1.jpg) | ![支付宝](https://ooo.0x0.ooo/2025/07/20/OYth4I.jpg) |
# SnowAdmin
<div>
<p>
<a href="https://github.com/WangFan-io/SnowAdmin" target="_blank">
<img src="https://img.shields.io/badge/License-MIT-%2343aefc" alt="License">
</a>
<a href="https://github.com/WangFan-io/SnowAdmin" target="_blank">
<img src="https://img.shields.io/badge/vue_.js-vue3_.x-%2300b42a" alt="Vue">
</a>
<a href="https://github.com/WangFan-io/SnowAdmin" target="_blank">
<img src="https://img.shields.io/badge/Vite-6x-%2311B337" alt="Vite">
</a>
<a href="https://github.com/WangFan-io/SnowAdmin" target="_blank">
<img alt="arco.design" src="https://img.shields.io/badge/arco.design-2.57.0-%23%2028%2C175%2C%2063">
</a>
</p>
</div>
### 介绍 📖
SnowAdmin 是一个清新优雅、高颜值且功能强大的后台管理模板,基于最新的前端技术栈,包括 Vue3, Vite6, TypeScript, Pinia。它内置了丰富的主题配置和组件,代码规范严谨,实现了自动化的文件路由系统。SnowAdmin 为您提供了一站式的后台管理解决方案,无需额外配置,开箱即用。同样是一个快速学习前沿技术的最佳实践。
### 版本 📦
**预览及文档**
项目预览地址:[SnowAdmin](http://115.190.79.132/#/login)
项目文档地址:[SnowAdmin-开发指南](http://115.190.79.132:81/)
**代码仓库**
| 平台 | 仓库地址 |
| ------ | ------------------------------------------------------ |
| GitHub | [Github 仓库](https://github.com/WangFan-io/SnowAdmin) |
| Gitee | [Gitee 仓库](https://gitee.com/wang_fan_w/SnowAdmin) |
> 完整版分支:main
>
> 极简版分支:main-thin
>
> ⚠️主要的维护在github上,提issue/pr请认准github主战场
>
> 大家也可以进wx群交流,二维码在介绍末尾
### 先行预览 🖼️
![登录页](https://ooo.0x0.ooo/2025/04/11/O0lhbG.png)
![首页](https://ooo.0x0.ooo/2025/04/11/O0lnVI.png)
![文件库](https://ooo.0x0.ooo/2025/04/11/O0l7qD.png)
![国际化](https://ooo.0x0.ooo/2025/04/11/O0lNAF.png)
![横向布局](https://ooo.0x0.ooo/2025/04/11/O0leQ6.png)
![混合布局](https://ooo.0x0.ooo/2025/04/11/O0lrCP.png)
![主题配置](https://ooo.0x0.ooo/2025/04/11/O0lKnb.png)
![黑暗模式-1](https://ooo.0x0.ooo/2025/04/11/O0lZ4l.png)
![黑暗模式-2](https://ooo.0x0.ooo/2025/04/11/O0lv6g.png)
![黑暗模式-3](https://ooo.0x0.ooo/2025/04/11/O0lgkB.png)
### 项目功能 🔨
- 清晰的项目架构:结构清晰,优雅易懂,代码全注释
- 前沿技术应用:采用 Vue3, Vite6, TypeScript等最新流行的技术栈
- 内置RBAC角色权限模型,实现路由、角色、按钮权限访问控制
- 使用 Pinia 替代 Vuex,轻量、简单、易用,集成 Pinia 持久化插件
- 支持 Arco-Design 组件大小切换、多主题布局、暗黑模式、i18n 国际化
- 使用 VueRouter 配置动态路由权限拦截、路由懒加载,支持页面按钮权限控制
- 使用 KeepAlive 对页面进行缓存,支持多级嵌套路由缓存
- 使用 Prettier 统一格式化代码,集成 ESLint、Stylelint 代码校验规范
- 使用 husky、lint-staged、commitlint等插件,规范提交信息
- 丰富的页面组件:内置多样页面和组件,包括 401、404、500 页面,以及布局组件、标签组件、主题配置组件等
### 环境准备 🏝️
确保你的环境满足以下要求(重要):
- **git**: 你需要 git 来克隆和管理项目版本。
- **NodeJS**: >=18.12.0,推荐 20.12.0 或更高。
- **pnpm**: >= 8.7.0,推荐最新版本。
### 安装使用步骤 📔
### 从 GitHub 获取代码 🔗
```bash
# 克隆代码
git clone https://github.com/WangFan-io/SnowAdmin.git
```
### 从 Gitee 获取代码 🔗
```bash
# 克隆代码
git clone https://gitee.com/wang_fan_w/SnowAdmin.git
```
### 安装依赖 📌
安装项目依赖
```bash
pnpm install
```
### 插件配置 🛠️
安装 Vue - Official,禁用 Vetur
- [Vue - Official](https://marketplace.visualstudio.com/items?itemName=Vue.volar) - Vue 服务插件
### 项目启动 🚀
```json
{
// 开发环境启动
"dev": "vite",
// 开发环境构建
"build:dev": "vue-tsc && vite build --mode development",
// 生产环境构建
"build:prod": "vue-tsc && vite build --mode production",
// 测试环境构建
"build:test": "vue-tsc && vite build --mode test",
// 预览环境启动
"preview": "vite preview"
}
```
### 文件资源目录 📚
```text
SnowAdmin
├─ .husky # husky 配置文件
├─ .vscode # VSCode 推荐配置
├─ build # vite项目配置目录
├─ public # 静态资源文件(该文件夹不会被打包)
├─ src
│ ├─ api # API 接口管理
│ ├─ assets # 静态资源文件
│ ├─ components # 全局组件
│ ├─ config # 全局配置项
│ ├─ directives # 全局自定义指令文件
│ ├─ globals # 全局函数
│ ├─ hooks # 常用 Hooks 封装
│ ├─ lang # 语言国际化 i18n
│ ├─ layout # 框架布局模块
│ ├─ mock # 本地数据mock
│ ├─ router # 路由管理
│ ├─ store # pinia store
│ ├─ style # 全局样式文件
│ ├─ typings # 全局 ts 声明
│ ├─ utils # 常用工具库
│ ├─ views # 项目所有页面
│ ├─ App.vue # 项目主组件
│ ├─ main.ts # 项目入口文件
│ └─ vite-env.d.ts # 指定 ts 识别 vue
├─ .editorconfig # 代码编辑器配置文件
├─ .env # 通用环境配置
├─ .env.development # 开发环境配置
├─ .env.production # 生产环境配置
├─ .env.test # 测试环境配置
├─ .eslintignore # 忽略 Eslint 校验
├─ .eslintrc.cjs # Eslint 校验配置文件
├─ .gitignore # 忽略 git 提交
├─ .prettierignore # 忽略 Prettier 格式化
├─ .prettierrc.cjs # Prettier 格式化配置
├─ .stylelintignore # 忽略 Stylelint 校验
├─ .stylelintrc.cjs # Stylelint 格式化配置
├─ commitlint.config.cjs # git 提交规范配置
├─ index.html # 入口 html
├─ LICENSE # 开源协议
├─ lint-staged.config.cjs # lint-staged 配置文件
├─ package-lock.json # 依赖包包版本锁
├─ package.json # 依赖包管理
├─ pnpm-lock.yaml # 依赖包包版本锁
├─ README.md # README 介绍
├─ tsconfig.json # typescript 全局配置
└─ vite.config.ts # vite 全局配置文件
```
### 浏览器支持 🌎
- 本地开发推荐使用 Chrome 最新版浏览器 [Download](https://www.google.com/intl/zh-CN/chrome/)。
- 生产环境支持现代浏览器,不再支持 IE 浏览器,更多浏览器可以查看 [Can I Use Es Module](https://caniuse.com/?search=ESModule)。
| ![IE](https://i.imgtg.com/2023/04/11/8z7ot.png) | ![Edge](https://i.imgtg.com/2023/04/11/8zr3p.png) | ![Firefox](https://i.imgtg.com/2023/04/11/8zKiU.png) | ![Chrome](https://i.imgtg.com/2023/04/11/8zNrx.png) | ![Safari](https://i.imgtg.com/2023/04/11/8zeGj.png) |
| :---------------------------------------------: | :-----------------------------------------------: | :--------------------------------------------------: | :-------------------------------------------------: | :-------------------------------------------------: |
| not support | last 2 versions | last 2 versions | last 2 versions | last 2 versions |
### 鸣谢列表 🧩
- [vue:https://v3.cn.vuejs.org/](https://v3.cn.vuejs.org/)
- [axios:https://github.com/axios/axios](https://github.com/axios/axios)
- [nprogress:https://github.com/rstacruz/nprogress](https://github.com/rstacruz/nprogress)
- [sortablejs:https://github.com/SortableJS/Sortabl](https://github.com/SortableJS/Sortable)
- [sass:https://github.com/sass/sass](https://github.com/sass/sass)
- [typescript:https://github.com/microsoft/TypeScript](https://github.com/microsoft/TypeScript)
- [vite:https://github.com/vitejs/vite](https://github.com/vitejs/vite)
- [wangeditor:https://github.com/wangeditor-team/wangEditor](https://github.com/wangeditor-team/wangEditor)
- [qrcodejs:https://github.com/davidshimjs/qrcodejs](https://github.com/davidshimjs/qrcodejs)
- [print-js:https://github.com/crabbly/Print.js](https://github.com/crabbly/Print.js)
- [eslint:https://github.com/eslint/eslint](https://github.com/eslint/eslint)
- [prettier:https://github.com/prettier/prettier](https://github.com/prettier/prettier)
- [arco.design:https://arco.design/](https://arco.design/)
- [pinyin-pro:https://github.com/zh-lx/pinyin-pro](https://github.com/zh-lx/pinyin-pro)
- [qrcode:https://www.npmjs.com/package/qrcode](https://www.npmjs.com/package/qrcode)
- [jsbarcode:https://github.com/lindell/JsBarcode/wiki/Options](https://github.com/lindell/JsBarcode/wiki/Options)
- [fingerprintjs2:https://www.npmjs.com/package/fingerprintjs2](https://www.npmjs.com/package/fingerprintjs2)
### 特别鸣谢 🎉
- [vue-next-admin:http://vuenextadmin.ccfast.cc/](http://vuenextadmin.ccfast.cc/)
- [Gi-admin:https://lin-97.github.io/gi-demo/](https://lin-97.github.io/gi-demo/#/home)
- [Geeker-Admin:https://admin.spicyboy.cn/](https://admin.spicyboy.cn/#/home/index)
感谢以上框架为本项目提供了帮助,项目中的很多设计思想值得参考和学习,再次感谢。
### 学习 & 交流 🏫
| SnowAdmin 交流群 |
| :---------------------------------------------------------------------------------------------------------: |
| ![微信图片_20250726141221](https://github.com/user-attachments/assets/8c1ebf3c-4630-487e-9a54-810fd4d6972c) |
使用过程中有各种问题也可以进群交流,欢迎大家积极参与
### 支持作者 🌟
如果觉得框架不错,或者已经在使用了,希望你可以去 [GitHub](https://github.com/WangFan-io/SnowAdmin) ⭐ Star,这将是对我极大的鼓励与支持。
### 免责条款 📫
您充分了解并同意,您必须为自己使用本服务及注册帐号下的一切行为负责,包括您所发表的任何内容以及由此产生的任何后果。您应对本服务中的内容自行加以判断,并自行承担因使用内容而引起的所有风险。
`SnowAdmin` 对网站上所显示的信息或资料的准确性、内容、完整性、合法性、可靠性、可操作性或可用性不承担任何责任。
`SnowAdmin` 二次开发使用者因为违法而触犯中华人民共和国法律的,一切后果自己负责,`SnowAdmin` 作者不承担任何责任。
本声明未涉及的问题参见国家有关法律法规,当本声明与国家法律法规冲突时,以国家法律法规为准。
### 学习 & 商用 🌈
`SnowAdmin` 是免费和开源的,可免费用于学习、商业使用 。
### 捐赠 💖
| 微信 | 支付宝 |
| :------------------------------------------------: | :--------------------------------------------------: |
| ![微信](https://ooo.0x0.ooo/2025/07/20/OYtFn1.jpg) | ![支付宝](https://ooo.0x0.ooo/2025/07/20/OYth4I.jpg) |
+73 -73
View File
@@ -1,73 +1,73 @@
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
import { PluginOption } from "vite";
import { vitePluginForArco } from "@arco-plugins/vite-vue";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import AutoImport from "unplugin-auto-import/vite";
import { ArcoResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";
import { viteMockServe } from "vite-plugin-mock";
import eslintPlugin from "vite-plugin-eslint";
/**
* 创建 vite 插件
* @param viteEnv
*/
export const createVitePlugins = (viteEnv: ViteEnv): (PluginOption | PluginOption[])[] => {
const env = viteEnv;
return [
vue(),
// esLint 报错信息显示在浏览器界面上
eslintPlugin(),
vitePluginForArco({
style: "css"
}),
createSvgIconsPlugin({
// 配置src下存放svg的路径,这里表示在src/assets/svgs文件夹下
iconDirs: [resolve(process.cwd(), "src/assets/svgs")],
symbolId: "icon-[dir]-[name]"
}),
AutoImport({
// 自动导入 Vue 相关函数,如:ref, reactive, toRef 等
imports: ["vue", "vue-router"],
// 自动导入的目录-自定义全局函数
dirs: ["src/globals"],
// arco组件的按需加载
resolvers: [ArcoResolver()],
// 解决eslint报错问题
eslintrc: {
// 这里先设置成true然后npm run dev 运行之后会生成 .eslintrc-auto-import.json 文件之后,在改为false
enabled: false,
filepath: "./.eslintrc-auto-import.json", // 生成的文件路径
globalsPropValue: true
},
// 配置文件生成位置
dts: "src/auto-import.d.ts"
}),
Components({
resolvers: [
// arco组件的按需加载
ArcoResolver({
sideEffect: true
})
],
// 自动加载组件的目录配置,默认的为 'src/components'
dirs: ["src/components"],
// 组件的有效文件扩展名
extensions: ["vue"],
// 配置文件生成位置
dts: "src/components.d.ts"
}),
viteMockServe({
mockPath: "./src/mock/", // 目录位置
logger: true, // 是否在控制台显示请求日志
supportTs: true, // 是否读取ts文件模块
localEnabled: env.VITE_APP_OPEN_MOCK === "true", // 设置是否启用本地mock文件
prodEnabled: env.VITE_APP_OPEN_MOCK === "true", // 设置打包是否启用mock功能
// 这样可以控制关闭mock的时候不让mock打包到最终代码内
injectCode: `
import { setupProdMockServer } from '../src/mock/index';
setupProdMockServer();
`
})
];
};
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
import { PluginOption } from "vite";
import { vitePluginForArco } from "@arco-plugins/vite-vue";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import AutoImport from "unplugin-auto-import/vite";
import { ArcoResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";
import { viteMockServe } from "vite-plugin-mock";
import eslintPlugin from "vite-plugin-eslint";
/**
* 创建 vite 插件
* @param viteEnv
*/
export const createVitePlugins = (viteEnv: ViteEnv): (PluginOption | PluginOption[])[] => {
const env = viteEnv;
return [
vue(),
// esLint 报错信息显示在浏览器界面上
eslintPlugin(),
vitePluginForArco({
style: "css"
}),
createSvgIconsPlugin({
// 配置src下存放svg的路径,这里表示在src/assets/svgs文件夹下
iconDirs: [resolve(process.cwd(), "src/assets/svgs")],
symbolId: "icon-[dir]-[name]"
}),
AutoImport({
// 自动导入 Vue 相关函数,如:ref, reactive, toRef 等
imports: ["vue", "vue-router"],
// 自动导入的目录-自定义全局函数
dirs: ["src/globals"],
// arco组件的按需加载
resolvers: [ArcoResolver()],
// 解决eslint报错问题
eslintrc: {
// 这里先设置成true然后npm run dev 运行之后会生成 .eslintrc-auto-import.json 文件之后,在改为false
enabled: false,
filepath: "./.eslintrc-auto-import.json", // 生成的文件路径
globalsPropValue: true
},
// 配置文件生成位置
dts: "src/auto-import.d.ts"
}),
Components({
resolvers: [
// arco组件的按需加载
ArcoResolver({
sideEffect: true
})
],
// 自动加载组件的目录配置,默认的为 'src/components'
dirs: ["src/components"],
// 组件的有效文件扩展名
extensions: ["vue"],
// 配置文件生成位置
dts: "src/components.d.ts"
}),
viteMockServe({
mockPath: "./src/mock/", // 目录位置
logger: true, // 是否在控制台显示请求日志
supportTs: true, // 是否读取ts文件模块
localEnabled: env.VITE_APP_OPEN_MOCK === "true", // 设置是否启用本地mock文件
prodEnabled: env.VITE_APP_OPEN_MOCK === "true", // 设置打包是否启用mock功能
// 这样可以控制关闭mock的时候不让mock打包到最终代码内
injectCode: `
import { setupProdMockServer } from '../src/mock/index';
setupProdMockServer();
`
})
];
};
+52 -52
View File
@@ -1,52 +1,52 @@
module.exports = {
ignores: [commit => commit.includes("init")],
extends: ["@commitlint/config-conventional"],
rules: {
"body-leading-blank": [2, "always"],
"footer-leading-blank": [1, "always"],
"header-max-length": [2, "always", 108],
"subject-empty": [2, "never"],
"type-empty": [2, "never"],
"type-enum": [
2,
"always",
[
"feat",
"fix",
"style",
"perf",
"refactor",
"test",
"chore",
"docs",
"workflow",
"build",
"ci",
"revert",
"wip",
"release",
"deps",
"merge",
"sync"
// feat:交新功能
// fix:bug修复
// style: 调整代码格式,未修改代码逻辑
// perf: 性能优化
// refactor:代码重构,既没修复bug也没有添加新功能
// test:增加测试
// chore: 其他修改(不在上述类型中的修改)
// docs:修改文档或注释
// workflow: 工作流
// build: 项目打包构建相关的配置修改
// ci: 持续集成相关
// revert: 恢复上一次提交(回滚)
// wip: work in progress 工作中 还没完成
// release: 发版
// deps: 依赖相关的修改
// merge 代码合并
// sync 同步主线或分支的Bug
// scope 说明 commit 影响的范围,比如数据层、控制层、视图层等等
]
]
}
};
module.exports = {
ignores: [commit => commit.includes("init")],
extends: ["@commitlint/config-conventional"],
rules: {
"body-leading-blank": [2, "always"],
"footer-leading-blank": [1, "always"],
"header-max-length": [2, "always", 108],
"subject-empty": [2, "never"],
"type-empty": [2, "never"],
"type-enum": [
2,
"always",
[
"feat",
"fix",
"style",
"perf",
"refactor",
"test",
"chore",
"docs",
"workflow",
"build",
"ci",
"revert",
"wip",
"release",
"deps",
"merge",
"sync"
// feat:交新功能
// fix:bug修复
// style: 调整代码格式,未修改代码逻辑
// perf: 性能优化
// refactor:代码重构,既没修复bug也没有添加新功能
// test:增加测试
// chore: 其他修改(不在上述类型中的修改)
// docs:修改文档或注释
// workflow: 工作流
// build: 项目打包构建相关的配置修改
// ci: 持续集成相关
// revert: 恢复上一次提交(回滚)
// wip: work in progress 工作中 还没完成
// release: 发版
// deps: 依赖相关的修改
// merge 代码合并
// sync 同步主线或分支的Bug
// scope 说明 commit 影响的范围,比如数据层、控制层、视图层等等
]
]
}
};
+8 -8
View File
@@ -1,8 +1,8 @@
module.exports = {
"*.{js,jsx,ts,tsx}": ["eslint --fix", "prettier --write"],
"{!(package)*.json,*.code-snippets,.!(browserslist)*rc}": ["prettier --write--parser json"],
"package.json": ["prettier --write"],
"*.vue": ["eslint --fix", "prettier --write", "stylelint --fix"],
"*.{scss,less,styl,html}": ["stylelint --fix", "prettier --write"],
"*.md": ["prettier --write"]
};
module.exports = {
"*.{js,jsx,ts,tsx}": ["eslint --fix", "prettier --write"],
"{!(package)*.json,*.code-snippets,.!(browserslist)*rc}": ["prettier --write--parser json"],
"package.json": ["prettier --write"],
"*.vue": ["eslint --fix", "prettier --write", "stylelint --fix"],
"*.{scss,less,styl,html}": ["stylelint --fix", "prettier --write"],
"*.md": ["prettier --write"]
};
+61 -61
View File
@@ -1,61 +1,61 @@
body {
margin: 0;
overflow: hidden;
}
.init-page {
width: 100vw;
height: 100vh;
left: 0;
top: 0;
display: flex;
align-items: center;
justify-content: center;
background: #fff;
}
/* HTML: <div class="snow-loader"></div> */
.snow-loader {
width: 45px;
aspect-ratio: 1;
--c: no-repeat linear-gradient(rgb(22, 93, 255) 0 0);
background:
var(--c) 0% 50%,
var(--c) 50% 50%,
var(--c) 100% 50%;
background-size: 20% 100%;
animation: l1 1s infinite linear;
}
@keyframes l1 {
0% {
background-size:
20% 100%,
20% 100%,
20% 100%;
}
33% {
background-size:
20% 10%,
20% 100%,
20% 100%;
}
50% {
background-size:
20% 100%,
20% 10%,
20% 100%;
}
66% {
background-size:
20% 100%,
20% 100%,
20% 10%;
}
100% {
background-size:
20% 100%,
20% 100%,
20% 100%;
}
}
body {
margin: 0;
overflow: hidden;
}
.init-page {
width: 100vw;
height: 100vh;
left: 0;
top: 0;
display: flex;
align-items: center;
justify-content: center;
background: #fff;
}
/* HTML: <div class="snow-loader"></div> */
.snow-loader {
width: 45px;
aspect-ratio: 1;
--c: no-repeat linear-gradient(rgb(22, 93, 255) 0 0);
background:
var(--c) 0% 50%,
var(--c) 50% 50%,
var(--c) 100% 50%;
background-size: 20% 100%;
animation: l1 1s infinite linear;
}
@keyframes l1 {
0% {
background-size:
20% 100%,
20% 100%,
20% 100%;
}
33% {
background-size:
20% 10%,
20% 100%,
20% 100%;
}
50% {
background-size:
20% 100%,
20% 10%,
20% 100%;
}
66% {
background-size:
20% 100%,
20% 100%,
20% 10%;
}
100% {
background-size:
20% 100%,
20% 100%,
20% 100%;
}
}
+18 -18
View File
@@ -1,18 +1,18 @@
<template>
<div>
<router-view />
</div>
</template>
<script setup lang="ts">
import { useThemeMethods } from "@/hooks/useThemeMethods";
// 初始化主题
const onTheme = () => {
let { initTheme } = useThemeMethods();
initTheme();
};
onTheme();
</script>
<style lang="scss" scoped></style>
<template>
<div>
<router-view />
</div>
</template>
<script setup lang="ts">
import { useThemeMethods } from "@/hooks/useThemeMethods";
// 初始化主题
const onTheme = () => {
let { initTheme } = useThemeMethods();
initTheme();
};
onTheme();
</script>
<style lang="scss" scoped></style>
+101 -101
View File
@@ -1,101 +1,101 @@
import axios from "axios";
import { Message } from "@arco-design/web-vue";
import { useUserInfoStore } from "@/store/modules/user-info";
import pinia from "@/store/index";
declare module "axios" {
interface AxiosInstance {
(config: AxiosRequestConfig): Promise<any>;
}
}
// 创建axios实例
const service = axios.create();
// 请求拦截器
service.interceptors.request.use(
function (config: any) {
// 发送请求之前做什么
// 获取token鉴权
let userInfo: any = {};
if (localStorage.getItem("user-info")) {
userInfo = JSON.parse(localStorage.getItem("user-info") as string);
}
if (userInfo?.token) {
// 有token,在请求头中携带token
config.headers.Authorization = userInfo.token;
}
return config;
},
function (error: any) {
// 请求错误
return Promise.reject(error);
}
);
// 响应拦截器
service.interceptors.response.use(
function (response: any) {
if (response.status != 200) {
Message.error("服务器异常,请联系管理员");
return Promise.reject(response.data);
}
let res = response.data;
if (res.code == 400) {
Message.error(res.msg);
return Promise.reject(res);
}
if (res.code == 403) {
// 清除 localStorage
localStorage.removeItem("user-info");
// 清除 Pinia store 中的 token 和用户信息
const userStore = useUserInfoStore(pinia);
userStore.logOut();
// 跳转到登录页(保留当前路径前缀,如 /admin)
const basePath = window.location.pathname.split("#")[0];
window.location.href = `${basePath}#/login`;
return Promise.reject(res);
}
if (res.code == 404) {
Message.error("请求连接超时");
return Promise.reject(res);
}
if (res.code != 200) {
Message.error(res.message);
return Promise.reject(res);
}
// 返回数据
return Promise.resolve(res);
},
function (error: any) {
// 处理 HTTP 错误状态码
if (error.response) {
if (error.response.status === 403) {
localStorage.removeItem("user-info");
const userStore = useUserInfoStore(pinia);
userStore.logOut();
Message.error("登录已过期,请重新登录");
const basePath = window.location.pathname.split("#")[0];
return (window.location.href = `${basePath}#/login`);
}
return Message.error(error.message || "请求失败");
}
}
);
export default service;
import axios from "axios";
import { Message } from "@arco-design/web-vue";
import { useUserInfoStore } from "@/store/modules/user-info";
import pinia from "@/store/index";
declare module "axios" {
interface AxiosInstance {
(config: AxiosRequestConfig): Promise<any>;
}
}
// 创建axios实例
const service = axios.create();
// 请求拦截器
service.interceptors.request.use(
function (config: any) {
// 发送请求之前做什么
// 获取token鉴权
let userInfo: any = {};
if (localStorage.getItem("user-info")) {
userInfo = JSON.parse(localStorage.getItem("user-info") as string);
}
if (userInfo?.token) {
// 有token,在请求头中携带token
config.headers.Authorization = userInfo.token;
}
return config;
},
function (error: any) {
// 请求错误
return Promise.reject(error);
}
);
// 响应拦截器
service.interceptors.response.use(
function (response: any) {
if (response.status != 200) {
Message.error("服务器异常,请联系管理员");
return Promise.reject(response.data);
}
let res = response.data;
if (res.code == 400) {
Message.error(res.msg);
return Promise.reject(res);
}
if (res.code == 403) {
// 清除 localStorage
localStorage.removeItem("user-info");
// 清除 Pinia store 中的 token 和用户信息
const userStore = useUserInfoStore(pinia);
userStore.logOut();
// 跳转到登录页(保留当前路径前缀,如 /admin)
const basePath = window.location.pathname.split("#")[0];
window.location.href = `${basePath}#/login`;
return Promise.reject(res);
}
if (res.code == 404) {
Message.error("请求连接超时");
return Promise.reject(res);
}
if (res.code != 200) {
Message.error(res.message);
return Promise.reject(res);
}
// 返回数据
return Promise.resolve(res);
},
function (error: any) {
// 处理 HTTP 错误状态码
if (error.response) {
if (error.response.status === 403) {
localStorage.removeItem("user-info");
const userStore = useUserInfoStore(pinia);
userStore.logOut();
Message.error("登录已过期,请重新登录");
const basePath = window.location.pathname.split("#")[0];
return (window.location.href = `${basePath}#/login`);
}
return Message.error(error.message || "请求失败");
}
}
);
export default service;
+9 -9
View File
@@ -1,9 +1,9 @@
import axios from "@/api";
export const getDashboardHomeAPI = (data: any) => {
return axios({
url: "/api/dashboard/home",
method: "post",
data
});
};
import axios from "@/api";
export const getDashboardHomeAPI = (data: any) => {
return axios({
url: "/api/dashboard/home",
method: "post",
data
});
};
+32 -32
View File
@@ -1,32 +1,32 @@
import axios from "@/api";
export const getRateListAPI = (data: any) => {
return axios({
url: "/api/rate/list",
method: "post",
data
});
};
export const getSyntaxListAPI = () => {
return axios({
url: "/api/rate/syntax",
method: "post"
});
};
export const setSyntaxAPI = (data: any) => {
return axios({
url: "/api/rate/set_syntax",
method: "post",
data
});
};
export const onSyncAPI = (data: any) => {
return axios({
url: "/api/rate/sync",
method: "post",
data
});
};
import axios from "@/api";
export const getRateListAPI = (data: any) => {
return axios({
url: "/api/rate/list",
method: "post",
data
});
};
export const getSyntaxListAPI = () => {
return axios({
url: "/api/rate/syntax",
method: "post"
});
};
export const setSyntaxAPI = (data: any) => {
return axios({
url: "/api/rate/set_syntax",
method: "post",
data
});
};
export const onSyncAPI = (data: any) => {
return axios({
url: "/api/rate/sync",
method: "post",
data
});
};
+58 -58
View File
@@ -1,58 +1,58 @@
import axios from "@/api";
// 获取菜单数据
export const getRoutersAPI = () => {
return axios({
url: "/api/auth/menu",
method: "get"
});
};
// 获取字典数据
export const getDictAPI = () => {
return axios({
url: "/mock/system/getDict",
method: "get"
});
};
// 获取部门数据
export const getDivisionAPI = () => {
return axios({
url: "/mock/system/getDivision",
method: "get"
});
};
// 获取角色数据
export const getRoleAPI = () => {
return axios({
url: "/mock/system/getRole",
method: "get"
});
};
// 获取账户数据
export const getAccountAPI = () => {
return axios({
url: "/mock/system/getAccount",
method: "get"
});
};
// 获取菜单管理列表
export const getMenuListAPI = () => {
return axios({
url: "/mock/menu/getMenuList",
method: "get"
});
};
// 根据角色获取权限数据
export const getUserPermissionAPI = (params: { role: string }) => {
return axios({
url: "/mock/menu/getUserPermission",
method: "get",
params
});
};
import axios from "@/api";
// 获取菜单数据
export const getRoutersAPI = () => {
return axios({
url: "/api/auth/menu",
method: "get"
});
};
// 获取字典数据
export const getDictAPI = () => {
return axios({
url: "/mock/system/getDict",
method: "get"
});
};
// 获取部门数据
export const getDivisionAPI = () => {
return axios({
url: "/mock/system/getDivision",
method: "get"
});
};
// 获取角色数据
export const getRoleAPI = () => {
return axios({
url: "/mock/system/getRole",
method: "get"
});
};
// 获取账户数据
export const getAccountAPI = () => {
return axios({
url: "/mock/system/getAccount",
method: "get"
});
};
// 获取菜单管理列表
export const getMenuListAPI = () => {
return axios({
url: "/mock/menu/getMenuList",
method: "get"
});
};
// 根据角色获取权限数据
export const getUserPermissionAPI = (params: { role: string }) => {
return axios({
url: "/mock/menu/getUserPermission",
method: "get",
params
});
};
+37 -37
View File
@@ -1,37 +1,37 @@
import axios from "@/api";
// 登录
export const loginAPI = (data: any) => {
return axios({
url: "/api/auth/login",
method: "post",
data
});
};
// 获取用户信息
export const getUserInfoAPI = (params?: any) => {
return axios({
url: "/api/auth/info",
method: "get",
params
});
};
// 安全设置
export const securityAPI = (data: any) => {
return axios({
url: "/api/auth/security",
method: "post",
data
});
};
// 设置密码
export const setPasswordAPI = (data: any) => {
return axios({
url: "/api/auth/set_password",
method: "post",
data
});
};
import axios from "@/api";
// 登录
export const loginAPI = (data: any) => {
return axios({
url: "/api/auth/login",
method: "post",
data
});
};
// 获取用户信息
export const getUserInfoAPI = (params?: any) => {
return axios({
url: "/api/auth/info",
method: "get",
params
});
};
// 安全设置
export const securityAPI = (data: any) => {
return axios({
url: "/api/auth/security",
method: "post",
data
});
};
// 设置密码
export const setPasswordAPI = (data: any) => {
return axios({
url: "/api/auth/set_password",
method: "post",
data
});
};
+33 -33
View File
@@ -1,33 +1,33 @@
import axios from "@/api";
export const getWalletListAPI = (data: any) => {
return axios({
url: "/api/wallet/list",
method: "post",
data
});
};
export const delWalletAPI = (data: any) => {
return axios({
url: "/api/wallet/del",
method: "post",
data
});
};
export const addWalletAPI = (data: any) => {
return axios({
url: "/api/wallet/add",
method: "post",
data
});
};
export const modWalletAPI = (data: any) => {
return axios({
url: "/api/wallet/mod",
method: "post",
data
});
};
import axios from "@/api";
export const getWalletListAPI = (data: any) => {
return axios({
url: "/api/wallet/list",
method: "post",
data
});
};
export const delWalletAPI = (data: any) => {
return axios({
url: "/api/wallet/del",
method: "post",
data
});
};
export const addWalletAPI = (data: any) => {
return axios({
url: "/api/wallet/add",
method: "post",
data
});
};
export const modWalletAPI = (data: any) => {
return axios({
url: "/api/wallet/mod",
method: "post",
data
});
};
+6 -6
View File
@@ -1,6 +1,6 @@
@font-face {
font-family: "AliFangYuanTi"; /*字体名-自定义*/
src: url("./AlimamaFangYuanTiVF-Thin.ttf"); /* 字体路径 */
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: "AliFangYuanTi"; /*字体名-自定义*/
src: url("./AlimamaFangYuanTiVF-Thin.ttf"); /* 字体路径 */
font-weight: normal;
font-style: normal;
}
+31 -31
View File
@@ -1,31 +1,31 @@
import { App, Directive } from "vue";
import antiShake from "@/directives/modules/global/anti-shake";
import throttle from "@/directives/modules/global/throttle";
import custom from "@/directives/modules/global/custom";
import hasPerm from "@/directives/modules/permission/has-perm";
import hasRole from "@/directives/modules/permission/has-role";
// 定义安装函数
// install 函数是一个对象中的方法,其作用是将一系列指令对象安装到 Vue 应用实例中,它自带两个参数:app 和 options
// app就是vue实例,options则是安装函数的参数(可选)
// install 方法的定义就插件对象,install 方法会在引入插件时自动被 vue 调用,并传参 vue 实例和 options
const group: { [key: string]: Directive } = {
antiShake,
throttle,
custom,
hasPerm,
hasRole
};
const directives = {
install(app: App<Element>) {
// 将一系列自定义指令对象安装到 Vue 应用实例中
for (const key in group) {
app.directive(key, group[key]);
}
}
};
// 导出安装函数
export default directives;
import { App, Directive } from "vue";
import antiShake from "@/directives/modules/global/anti-shake";
import throttle from "@/directives/modules/global/throttle";
import custom from "@/directives/modules/global/custom";
import hasPerm from "@/directives/modules/permission/has-perm";
import hasRole from "@/directives/modules/permission/has-role";
// 定义安装函数
// install 函数是一个对象中的方法,其作用是将一系列指令对象安装到 Vue 应用实例中,它自带两个参数:app 和 options
// app就是vue实例,options则是安装函数的参数(可选)
// install 方法的定义就插件对象,install 方法会在引入插件时自动被 vue 调用,并传参 vue 实例和 options
const group: { [key: string]: Directive } = {
antiShake,
throttle,
custom,
hasPerm,
hasRole
};
const directives = {
install(app: App<Element>) {
// 将一系列自定义指令对象安装到 Vue 应用实例中
for (const key in group) {
app.directive(key, group[key]);
}
}
};
// 导出安装函数
export default directives;
+50 -50
View File
@@ -1,50 +1,50 @@
import { Directive } from "vue";
const antiShake: Directive = {
mounted(el, binding) {
// 判断是否是函数,防抖指令必须绑定函数
if (typeof binding.value != "function") {
return console.warn("Anti-shake instructions must be bound to a function");
}
let timeout: any = null;
// 给el添加自定义事件-防抖函数
el.__onClick__ = () => {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
// 由于绑定的是函数,这里直接调用绑定之即可(也就是调用绑定的函数)
binding.value();
}, 500);
};
// 监听点击事件,点击后调用绑定的自定义事件
el.addEventListener("click", el.__onClick__);
},
beforeUnmount(el) {
el.removeEventListener("click", el.__onClick__);
}
};
export default antiShake;
// 每个生命周期都有两个参数,el、binding
// 其中el为绑定的dom元素,binding为指令的传入值
// app.directive("focus", {
// 在绑定元素的 attribute 前
// 或事件监听器应用前调用
// created(el, binding, vnode) {
// // 下面会介绍各个参数的细节
// },
// // 在元素被插入到 DOM 前调用
// beforeMount(el, binding, vnode) {},
// // 在绑定元素的父组件
// // 及他自己的所有子节点都挂载完成后调用
// mounted(el, binding, vnode) {},
// // 绑定元素的父组件更新前调用
// beforeUpdate(el, binding, vnode, prevVnode) {},
// // 在绑定元素的父组件
// // 及他自己的所有子节点都更新后调用
// updated(el, binding, vnode, prevVnode) {},
// // 绑定元素的父组件卸载前调用
// beforeUnmount(el, binding, vnode) {},
// // 绑定元素的父组件卸载后调用
// unmounted(el, binding, vnode) {}
// });
import { Directive } from "vue";
const antiShake: Directive = {
mounted(el, binding) {
// 判断是否是函数,防抖指令必须绑定函数
if (typeof binding.value != "function") {
return console.warn("Anti-shake instructions must be bound to a function");
}
let timeout: any = null;
// 给el添加自定义事件-防抖函数
el.__onClick__ = () => {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
// 由于绑定的是函数,这里直接调用绑定之即可(也就是调用绑定的函数)
binding.value();
}, 500);
};
// 监听点击事件,点击后调用绑定的自定义事件
el.addEventListener("click", el.__onClick__);
},
beforeUnmount(el) {
el.removeEventListener("click", el.__onClick__);
}
};
export default antiShake;
// 每个生命周期都有两个参数,el、binding
// 其中el为绑定的dom元素,binding为指令的传入值
// app.directive("focus", {
// 在绑定元素的 attribute 前
// 或事件监听器应用前调用
// created(el, binding, vnode) {
// // 下面会介绍各个参数的细节
// },
// // 在元素被插入到 DOM 前调用
// beforeMount(el, binding, vnode) {},
// // 在绑定元素的父组件
// // 及他自己的所有子节点都挂载完成后调用
// mounted(el, binding, vnode) {},
// // 绑定元素的父组件更新前调用
// beforeUpdate(el, binding, vnode, prevVnode) {},
// // 在绑定元素的父组件
// // 及他自己的所有子节点都更新后调用
// updated(el, binding, vnode, prevVnode) {},
// // 绑定元素的父组件卸载前调用
// beforeUnmount(el, binding, vnode) {},
// // 绑定元素的父组件卸载后调用
// unmounted(el, binding, vnode) {}
// });
+13 -13
View File
@@ -1,13 +1,13 @@
import { Directive } from "vue";
const custom: Directive = {
mounted(el, binding) {
el.__onClick__ = () => {
let { goodsId, event } = binding.value;
event(goodsId);
};
el.addEventListener("click", el.__onClick__);
}
};
export default custom;
import { Directive } from "vue";
const custom: Directive = {
mounted(el, binding) {
el.__onClick__ = () => {
let { goodsId, event } = binding.value;
event(goodsId);
};
el.addEventListener("click", el.__onClick__);
}
};
export default custom;
+31 -31
View File
@@ -1,31 +1,31 @@
import { Directive } from "vue";
const throttle: Directive = {
mounted(el, binding) {
if (typeof binding.value != "function") {
return console.warn("The throttling instruction must be bound to a function");
}
let countDown = 0;
let timer: any = null;
el.__onClick__ = () => {
if (timer) return;
if (countDown == 0) {
binding.value();
countDown = 1;
}
timer = setInterval(() => {
countDown--;
if (countDown <= 0) {
clearInterval(timer);
timer = null;
}
}, 1000);
};
el.addEventListener("click", el.__onClick__);
},
beforeUnmount(el) {
el.removeEventListener("click", el.__onClick__);
}
};
export default throttle;
import { Directive } from "vue";
const throttle: Directive = {
mounted(el, binding) {
if (typeof binding.value != "function") {
return console.warn("The throttling instruction must be bound to a function");
}
let countDown = 0;
let timer: any = null;
el.__onClick__ = () => {
if (timer) return;
if (countDown == 0) {
binding.value();
countDown = 1;
}
timer = setInterval(() => {
countDown--;
if (countDown <= 0) {
clearInterval(timer);
timer = null;
}
}, 1000);
};
el.addEventListener("click", el.__onClick__);
},
beforeUnmount(el) {
el.removeEventListener("click", el.__onClick__);
}
};
export default throttle;
+21 -21
View File
@@ -1,21 +1,21 @@
import { computed } from "vue";
import { useWindowSize } from "@vueuse/core";
interface DeviceSize {
isPc: ComputedRef<boolean>;
isPad: ComputedRef<boolean>;
isMobile: ComputedRef<boolean>;
}
/**
* 小于 768px:适配移动设备(如手机)。
* 768px - 1024px:适配平板设备。
* 大于 1024px:适配桌面设备。
* @returns PC窗口isPc, 平板窗口isPad, 移动端窗口isMobile
*/
export const useDevicesSize = (): DeviceSize => {
const { width } = useWindowSize();
const isPc = computed(() => width.value > 1024);
const isPad = computed(() => width.value > 768 && width.value <= 1024);
const isMobile = computed(() => width.value <= 768);
return { isPc, isPad, isMobile };
};
import { computed } from "vue";
import { useWindowSize } from "@vueuse/core";
interface DeviceSize {
isPc: ComputedRef<boolean>;
isPad: ComputedRef<boolean>;
isMobile: ComputedRef<boolean>;
}
/**
* 小于 768px:适配移动设备(如手机)。
* 768px - 1024px:适配平板设备。
* 大于 1024px:适配桌面设备。
* @returns PC窗口isPc, 平板窗口isPad, 移动端窗口isMobile
*/
export const useDevicesSize = (): DeviceSize => {
const { width } = useWindowSize();
const isPc = computed(() => width.value > 1024);
const isPad = computed(() => width.value > 768 && width.value <= 1024);
const isMobile = computed(() => width.value <= 768);
return { isPc, isPad, isMobile };
};
+3 -3
View File
@@ -1,3 +1,3 @@
// 用于全局使用globalProperties
import { getCurrentInstance, ComponentInternalInstance } from "vue";
export default () => (getCurrentInstance() as ComponentInternalInstance).appContext.config.globalProperties;
// 用于全局使用globalProperties
import { getCurrentInstance, ComponentInternalInstance } from "vue";
export default () => (getCurrentInstance() as ComponentInternalInstance).appContext.config.globalProperties;
+29 -29
View File
@@ -1,29 +1,29 @@
/**
* 菜单处理hooks,内置多种菜单处理场景
* @returns 菜单处理方法
*/
export const useMenuMethod = () => {
/**
* 多级菜单的显示隐藏
* @param {Menu.MenuOptions} item 菜单的item
* @returns type:1为目录,并且不隐藏,返回true,否则返回false
*/
const menuShow = (item: Menu.MenuOptions) => {
if (item.meta.type == 1 && !item.meta.hide) return true;
return false;
};
/**
* 单级菜单的显示隐藏
* @param {Menu.MenuOptions} item 菜单的item
* @returns type:2为菜单,并且单级菜单不隐藏,返回true,否则返回false
*/
const aMenuShow = (item: Menu.MenuOptions) => {
if (item.meta.type == 2 && !item.meta.hide) return true;
return false;
};
return {
menuShow,
aMenuShow
};
};
/**
* 菜单处理hooks,内置多种菜单处理场景
* @returns 菜单处理方法
*/
export const useMenuMethod = () => {
/**
* 多级菜单的显示隐藏
* @param {Menu.MenuOptions} item 菜单的item
* @returns type:1为目录,并且不隐藏,返回true,否则返回false
*/
const menuShow = (item: Menu.MenuOptions) => {
if (item.meta.type == 1 && !item.meta.hide) return true;
return false;
};
/**
* 单级菜单的显示隐藏
* @param {Menu.MenuOptions} item 菜单的item
* @returns type:2为菜单,并且单级菜单不隐藏,返回true,否则返回false
*/
const aMenuShow = (item: Menu.MenuOptions) => {
if (item.meta.type == 2 && !item.meta.hide) return true;
return false;
};
return {
menuShow,
aMenuShow
};
};
+83 -83
View File
@@ -1,83 +1,83 @@
import pinia from "@/store/index";
import { storeToRefs } from "pinia";
import { useRouteConfigStore } from "@/store/modules/route-config";
import { findCategoryById, findPathOfParentNode } from "@/utils/tree-tools";
/**
* 路由处理hooks,内置多种路由处理场景
* @returns 路由方法
*/
export const useRoutingMethod = () => {
/**
* 从一维路由中查找路由
* @param {string} path 路由的path
* @returns 查找到的路由,undefined则表示未找到
*/
const findLinearArray = (path: string) => {
const routerStore = useRouteConfigStore(pinia);
const { routeTree } = storeToRefs(routerStore);
return findCategoryById(routeTree.value, "path", path);
};
/**
* 根据当前路由找到所有直属父级路由
* @param {string} path 路由的path
* @returns 查找到的所有父级路由,未找到则null
*/
const getAllParentRoute = (path: string) => {
const routerStore = useRouteConfigStore(pinia);
const { routeTree } = storeToRefs(routerStore);
return findPathOfParentNode(routeTree.value, "path", path);
};
/**
* 从一维路由中判断路由是否存在
* @param {string} key 路由的name
* @returns 路由是否存在,true存在 false不存在
*/
const hasRoute = (key: string) => {
const routerStore = useRouteConfigStore(pinia);
const { routeList } = storeToRefs(routerStore);
return routeList.value.some((item: Menu.MenuOptions) => item.name == key);
};
/**
* 从tabs路由中查找路由
* @param {string} key 路由的name
* @returns 查找到的路由,undefined则表示未找到
*/
const findTagsList = (key: string) => {
const routerStore = useRouteConfigStore(pinia);
const { tabsList } = storeToRefs(routerStore);
return tabsList.value.find((item: Menu.MenuOptions) => item.name == key);
};
/**
* 处理外链跳转,打开一个新窗口并根据url跳转
* @param {any} route 路由
*/
const openExternalLinks = (route: any) => {
// 处理外链跳转
if (route.meta.link && !route.meta.iframe) {
window.open(route.meta.link as string, "_blank");
}
};
/**
* 检测是否是动态匹配路由,如果是动态匹配路由,则path必然带有"/:"字样,例如:/user/:id
* @param {string} path 路由path
* @returns 是否是动态匹配路由
*/
const isDynamicRoute = (path: string) => {
return path.includes("/:");
};
return {
findLinearArray,
getAllParentRoute,
findTagsList,
openExternalLinks,
isDynamicRoute,
hasRoute
};
};
import pinia from "@/store/index";
import { storeToRefs } from "pinia";
import { useRouteConfigStore } from "@/store/modules/route-config";
import { findCategoryById, findPathOfParentNode } from "@/utils/tree-tools";
/**
* 路由处理hooks,内置多种路由处理场景
* @returns 路由方法
*/
export const useRoutingMethod = () => {
/**
* 从一维路由中查找路由
* @param {string} path 路由的path
* @returns 查找到的路由,undefined则表示未找到
*/
const findLinearArray = (path: string) => {
const routerStore = useRouteConfigStore(pinia);
const { routeTree } = storeToRefs(routerStore);
return findCategoryById(routeTree.value, "path", path);
};
/**
* 根据当前路由找到所有直属父级路由
* @param {string} path 路由的path
* @returns 查找到的所有父级路由,未找到则null
*/
const getAllParentRoute = (path: string) => {
const routerStore = useRouteConfigStore(pinia);
const { routeTree } = storeToRefs(routerStore);
return findPathOfParentNode(routeTree.value, "path", path);
};
/**
* 从一维路由中判断路由是否存在
* @param {string} key 路由的name
* @returns 路由是否存在,true存在 false不存在
*/
const hasRoute = (key: string) => {
const routerStore = useRouteConfigStore(pinia);
const { routeList } = storeToRefs(routerStore);
return routeList.value.some((item: Menu.MenuOptions) => item.name == key);
};
/**
* 从tabs路由中查找路由
* @param {string} key 路由的name
* @returns 查找到的路由,undefined则表示未找到
*/
const findTagsList = (key: string) => {
const routerStore = useRouteConfigStore(pinia);
const { tabsList } = storeToRefs(routerStore);
return tabsList.value.find((item: Menu.MenuOptions) => item.name == key);
};
/**
* 处理外链跳转,打开一个新窗口并根据url跳转
* @param {any} route 路由
*/
const openExternalLinks = (route: any) => {
// 处理外链跳转
if (route.meta.link && !route.meta.iframe) {
window.open(route.meta.link as string, "_blank");
}
};
/**
* 检测是否是动态匹配路由,如果是动态匹配路由,则path必然带有"/:"字样,例如:/user/:id
* @param {string} path 路由path
* @returns 是否是动态匹配路由
*/
const isDynamicRoute = (path: string) => {
return path.includes("/:");
};
return {
findLinearArray,
getAllParentRoute,
findTagsList,
openExternalLinks,
isDynamicRoute,
hasRoute
};
};
+99 -99
View File
@@ -1,99 +1,99 @@
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
import { generate, getRgbStr } from "@arco-design/color";
/**
* 主题处理hooks,内置多种主题处理场景
* @returns 主题方法
*/
export const useThemeMethods = () => {
/**
* @description: 初始化主题
*/
const initTheme = () => {
// 黑暗模式和主题色
setDarkMode();
// 色弱模式和灰色模式
const themeStore = useThemeConfig();
const { grayMode } = storeToRefs(themeStore);
if (grayMode.value) {
setGray();
} else {
setColorWeak();
}
};
/**
* @description: 暗黑模式
*/
const setDarkMode = () => {
const themeStore = useThemeConfig();
const { darkMode, asideDark } = storeToRefs(themeStore);
if (darkMode.value) {
// 设置为暗黑主题
document.body.setAttribute("arco-theme", "dark");
asideDark.value = false; // 黑暗模式与侧边栏深色互斥
} else {
// 恢复亮色主题
document.body.removeAttribute("arco-theme");
}
// 黑暗模式切换后需要更新主题色
setThemeColor();
};
/**
* @description: 主题色设置
*/
const setThemeColor = () => {
const themeStore = useThemeConfig();
const { themeColor, darkMode } = storeToRefs(themeStore);
// 对于给定的颜色,使用算法生成包含10种颜色的渐变样本。这适用于光模式和暗模式。
let list = generate(themeColor.value, { list: true, dark: darkMode.value });
list.forEach((color: string, index: number) => {
// https://arco.design/palette/list
// arco的颜色等级为1-10,这里需要index+1
document.body.style.setProperty(`--primary-${index + 1}`, getRgbStr(color));
});
};
/**
* @description: 色弱模式
*/
const setColorWeak = () => {
// 获取html
const htmlCase = document.querySelector("html") as HTMLHtmlElement | null;
if (!htmlCase) return;
const themeStore = useThemeConfig();
const { colorWeakMode, grayMode } = storeToRefs(themeStore);
if (colorWeakMode.value) {
grayMode.value = false; // 色弱模式和灰色模式互斥
htmlCase.style.filter = "invert(80%)"; // 反转色80%
} else {
htmlCase.style.filter = "";
}
};
/**
* @description: 灰色模式
*/
const setGray = () => {
// 获取html
const htmlCase = document.querySelector("html") as HTMLHtmlElement | null;
if (!htmlCase) return;
const themeStore = useThemeConfig();
const { colorWeakMode, grayMode } = storeToRefs(themeStore);
if (grayMode.value) {
colorWeakMode.value = false; // 色弱模式和灰色模式互斥
htmlCase.style.filter = "grayscale(100%)"; // 灰度100%
} else {
htmlCase.style.filter = "";
}
};
return {
initTheme,
setDarkMode,
setThemeColor,
setColorWeak,
setGray
};
};
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
import { generate, getRgbStr } from "@arco-design/color";
/**
* 主题处理hooks,内置多种主题处理场景
* @returns 主题方法
*/
export const useThemeMethods = () => {
/**
* @description: 初始化主题
*/
const initTheme = () => {
// 黑暗模式和主题色
setDarkMode();
// 色弱模式和灰色模式
const themeStore = useThemeConfig();
const { grayMode } = storeToRefs(themeStore);
if (grayMode.value) {
setGray();
} else {
setColorWeak();
}
};
/**
* @description: 暗黑模式
*/
const setDarkMode = () => {
const themeStore = useThemeConfig();
const { darkMode, asideDark } = storeToRefs(themeStore);
if (darkMode.value) {
// 设置为暗黑主题
document.body.setAttribute("arco-theme", "dark");
asideDark.value = false; // 黑暗模式与侧边栏深色互斥
} else {
// 恢复亮色主题
document.body.removeAttribute("arco-theme");
}
// 黑暗模式切换后需要更新主题色
setThemeColor();
};
/**
* @description: 主题色设置
*/
const setThemeColor = () => {
const themeStore = useThemeConfig();
const { themeColor, darkMode } = storeToRefs(themeStore);
// 对于给定的颜色,使用算法生成包含10种颜色的渐变样本。这适用于光模式和暗模式。
let list = generate(themeColor.value, { list: true, dark: darkMode.value });
list.forEach((color: string, index: number) => {
// https://arco.design/palette/list
// arco的颜色等级为1-10,这里需要index+1
document.body.style.setProperty(`--primary-${index + 1}`, getRgbStr(color));
});
};
/**
* @description: 色弱模式
*/
const setColorWeak = () => {
// 获取html
const htmlCase = document.querySelector("html") as HTMLHtmlElement | null;
if (!htmlCase) return;
const themeStore = useThemeConfig();
const { colorWeakMode, grayMode } = storeToRefs(themeStore);
if (colorWeakMode.value) {
grayMode.value = false; // 色弱模式和灰色模式互斥
htmlCase.style.filter = "invert(80%)"; // 反转色80%
} else {
htmlCase.style.filter = "";
}
};
/**
* @description: 灰色模式
*/
const setGray = () => {
// 获取html
const htmlCase = document.querySelector("html") as HTMLHtmlElement | null;
if (!htmlCase) return;
const themeStore = useThemeConfig();
const { colorWeakMode, grayMode } = storeToRefs(themeStore);
if (grayMode.value) {
colorWeakMode.value = false; // 色弱模式和灰色模式互斥
htmlCase.style.filter = "grayscale(100%)"; // 灰度100%
} else {
htmlCase.style.filter = "";
}
};
return {
initTheme,
setDarkMode,
setThemeColor,
setColorWeak,
setGray
};
};
+39 -39
View File
@@ -1,39 +1,39 @@
import { createI18n } from "vue-i18n";
import zhCN from "@/lang/modules/zhCN";
import enUS from "@/lang/modules/enUS";
/* 获取语言 */
const getLang = () => {
let store = localStorage.getItem("theme-config");
if (store) {
return JSON.parse(store)?.language || "zh-CN";
} else {
return "zh-CN";
}
};
/* 这里必须是messages名称 */
const messages = {
"zh-CN": zhCN,
"en-US": enUS
};
const i18n = createI18n({
legacy: false, // Composition API模式需要设为false
globalInjection: true, // 全局生效: $
locale: getLang(), // 默认语言
messages, // 数据源
missing: (_: string, key: string) => {
return removeBeforeFirstDot(key);
}
});
/**
* @param { string } str 国际化key
* @returns 去掉第一个点之前的字符串,例如:"menu.home" => "home",否则返回原字符串
*/
function removeBeforeFirstDot(str: string) {
const dotIndex = str.indexOf(".");
return dotIndex >= 0 ? str.slice(dotIndex + 1) : str;
}
export default i18n;
import { createI18n } from "vue-i18n";
import zhCN from "@/lang/modules/zhCN";
import enUS from "@/lang/modules/enUS";
/* 获取语言 */
const getLang = () => {
let store = localStorage.getItem("theme-config");
if (store) {
return JSON.parse(store)?.language || "zh-CN";
} else {
return "zh-CN";
}
};
/* 这里必须是messages名称 */
const messages = {
"zh-CN": zhCN,
"en-US": enUS
};
const i18n = createI18n({
legacy: false, // Composition API模式需要设为false
globalInjection: true, // 全局生效: $
locale: getLang(), // 默认语言
messages, // 数据源
missing: (_: string, key: string) => {
return removeBeforeFirstDot(key);
}
});
/**
* @param { string } str 国际化key
* @returns 去掉第一个点之前的字符串,例如:"menu.home" => "home",否则返回原字符串
*/
function removeBeforeFirstDot(str: string) {
const dotIndex = str.indexOf(".");
return dotIndex >= 0 ? str.slice(dotIndex + 1) : str;
}
export default i18n;
+119 -119
View File
@@ -1,119 +1,119 @@
export default {
system: {
["login"]: "login",
["not-power"]: "No permission",
["not-found"]: "Page not found",
["zh-CN"]: "中文",
["en-US"]: "English",
["refresh"]: "refresh",
["close-current"]: "close current",
["close-left-side"]: "close left side",
["close-right-side"]: "close right side",
["close-other"]: "close other",
["close-all"]: "close all",
["switch-to-night-mode"]: "switch to night mode",
["switch-to-daytime-mode"]: "switch to daytime mode",
["full-screen"]: "full screen",
["exit-full-screen"]: "exit full screen",
["system-settings"]: "system settings",
["theme-settings"]: "theme settings",
["personal-information"]: "personal information",
["change-password"]: "change password",
["project-address"]: "project address",
["logout"]: "logout",
["notice"]: "Notice",
["message"]: "Message",
["backlog"]: "Backlog",
["switch-language-to-preview"]: "Please switch the language to preview the internationalization effect",
["please-enter-something"]: "Please enter something"
},
menu: {
["home"]: "home",
["file"]: "file",
["document-library"]: "document-library",
["table"]: "table",
["common-table"]: "common-table",
["custom-table"]: "custom-table",
["form"]: "form",
["common-form"]: "common-form",
["step-form"]: "step-form",
["multilevel"]: "multilevel",
["second-1"]: "second-1",
["second-2"]: "second-2",
["third-1"]: "third-1",
["third-2"]: "third-2",
["third-3"]: "third-3",
["third-4"]: "third-4",
["third-5"]: "third-5",
["third-6"]: "third-6",
["third-7"]: "third-7",
["third-8"]: "third-8",
["third-9"]: "third-9",
["component"]: "component",
["player"]: "player",
["print"]: "print",
["draggable"]: "draggable",
["editor"]: "editor",
["newbie"]: "newbie",
["icon-selector"]: "icon-selector",
["user-center"]: "user-center",
["fingerprintjs2"]: "fingerprintjs2",
["barcode"]: "barcode",
["qrcode"]: "qrcode",
["pinyin"]: "pinyin",
["markdown"]: "Markdown",
["directive"]: "directive",
["anti-shake"]: "anti-shake",
["throttle"]: "throttle",
["test-directive"]: "test-directive",
["personal"]: "personal",
["userinfo"]: "userinfo",
["user-settings"]: "user-settings",
["system"]: "system",
["account"]: "account",
["role"]: "role",
["menu"]: "menu",
["division"]: "division",
["dictionary"]: "dictionary",
["log"]: "log",
["about"]: "about",
["link"]: "link",
["internal"]: "internal",
["uigradients"]: "uigradients",
["color-taking-tool"]: "color-taking-tool",
["grid-generator"]: "grid-generator",
["external"]: "external",
["vue"]: "vue",
["vite"]: "vite",
["github"]: "github",
["SnowAdmin-Docs"]: "SnowAdmin-Docs",
["juejin"]: "juejin",
["disable-menu"]: "disable-menu",
["hide-menu"]: "hide-menu",
["system-monitor"]: "system monitor",
["onlineuser"]: "online user",
["crontab"]: "crontab",
["crontab-logs"]: "crontab logs",
["i18n"]: "i18n",
["amap"]: "amap",
["permission"]: "permission",
["btn-perm"]: "btn perm",
["admin-page"]: "admin page",
["common-page"]: "common page",
["functions"]: "functions",
["routing-operation"]: "routing operation",
["common-route"]: "common route",
["dynamic-route"]: "dynamic route",
["audio"]: "audio",
["recorder"]: "recorder",
["virtual-list"]: "virtual-list",
["common-tools"]: "common tools",
["tree-tools"]: "tree-tools",
["file-tools"]: "file-tools",
["verify-tools"]: "verify tools",
["common-layouts"]: "common layouts",
["data-screen"]: "data screen",
["thin-preview"]: "thin preview",
["test"]: "test"
}
};
export default {
system: {
["login"]: "login",
["not-power"]: "No permission",
["not-found"]: "Page not found",
["zh-CN"]: "中文",
["en-US"]: "English",
["refresh"]: "refresh",
["close-current"]: "close current",
["close-left-side"]: "close left side",
["close-right-side"]: "close right side",
["close-other"]: "close other",
["close-all"]: "close all",
["switch-to-night-mode"]: "switch to night mode",
["switch-to-daytime-mode"]: "switch to daytime mode",
["full-screen"]: "full screen",
["exit-full-screen"]: "exit full screen",
["system-settings"]: "system settings",
["theme-settings"]: "theme settings",
["personal-information"]: "personal information",
["change-password"]: "change password",
["project-address"]: "project address",
["logout"]: "logout",
["notice"]: "Notice",
["message"]: "Message",
["backlog"]: "Backlog",
["switch-language-to-preview"]: "Please switch the language to preview the internationalization effect",
["please-enter-something"]: "Please enter something"
},
menu: {
["home"]: "home",
["file"]: "file",
["document-library"]: "document-library",
["table"]: "table",
["common-table"]: "common-table",
["custom-table"]: "custom-table",
["form"]: "form",
["common-form"]: "common-form",
["step-form"]: "step-form",
["multilevel"]: "multilevel",
["second-1"]: "second-1",
["second-2"]: "second-2",
["third-1"]: "third-1",
["third-2"]: "third-2",
["third-3"]: "third-3",
["third-4"]: "third-4",
["third-5"]: "third-5",
["third-6"]: "third-6",
["third-7"]: "third-7",
["third-8"]: "third-8",
["third-9"]: "third-9",
["component"]: "component",
["player"]: "player",
["print"]: "print",
["draggable"]: "draggable",
["editor"]: "editor",
["newbie"]: "newbie",
["icon-selector"]: "icon-selector",
["user-center"]: "user-center",
["fingerprintjs2"]: "fingerprintjs2",
["barcode"]: "barcode",
["qrcode"]: "qrcode",
["pinyin"]: "pinyin",
["markdown"]: "Markdown",
["directive"]: "directive",
["anti-shake"]: "anti-shake",
["throttle"]: "throttle",
["test-directive"]: "test-directive",
["personal"]: "personal",
["userinfo"]: "userinfo",
["user-settings"]: "user-settings",
["system"]: "system",
["account"]: "account",
["role"]: "role",
["menu"]: "menu",
["division"]: "division",
["dictionary"]: "dictionary",
["log"]: "log",
["about"]: "about",
["link"]: "link",
["internal"]: "internal",
["uigradients"]: "uigradients",
["color-taking-tool"]: "color-taking-tool",
["grid-generator"]: "grid-generator",
["external"]: "external",
["vue"]: "vue",
["vite"]: "vite",
["github"]: "github",
["SnowAdmin-Docs"]: "SnowAdmin-Docs",
["juejin"]: "juejin",
["disable-menu"]: "disable-menu",
["hide-menu"]: "hide-menu",
["system-monitor"]: "system monitor",
["onlineuser"]: "online user",
["crontab"]: "crontab",
["crontab-logs"]: "crontab logs",
["i18n"]: "i18n",
["amap"]: "amap",
["permission"]: "permission",
["btn-perm"]: "btn perm",
["admin-page"]: "admin page",
["common-page"]: "common page",
["functions"]: "functions",
["routing-operation"]: "routing operation",
["common-route"]: "common route",
["dynamic-route"]: "dynamic route",
["audio"]: "audio",
["recorder"]: "recorder",
["virtual-list"]: "virtual-list",
["common-tools"]: "common tools",
["tree-tools"]: "tree-tools",
["file-tools"]: "file-tools",
["verify-tools"]: "verify tools",
["common-layouts"]: "common layouts",
["data-screen"]: "data screen",
["thin-preview"]: "thin preview",
["test"]: "test"
}
};
+128 -128
View File
@@ -1,128 +1,128 @@
export default {
system: {
["login"]: "登录",
["not-power"]: "没有权限",
["not-found"]: "未找到页面",
["zh-CN"]: "中文",
["en-US"]: "English",
["refresh"]: "刷新",
["close-current"]: "关闭当前",
["close-left-side"]: "关闭左侧",
["close-right-side"]: "关闭右侧",
["close-other"]: "关闭其它",
["close-all"]: "关闭全部",
["switch-to-night-mode"]: "切换黑夜模式",
["switch-to-daytime-mode"]: "切换白天模式",
["full-screen"]: "全屏",
["exit-full-screen"]: "退出全屏",
["system-settings"]: "系统设置",
["theme-settings"]: "主题设置",
["personal-information"]: "个人信息",
["change-password"]: "修改密码",
["project-address"]: "项目地址",
["logout"]: "退出登录",
["notice"]: "通知",
["message"]: "消息",
["backlog"]: "待办",
["switch-language-to-preview"]: "请切换语言来预览国际化效果",
["please-enter-something"]: "请输入"
},
menu: {
["home"]: "首页",
["wallet"]: "钱包管理",
["order"]: "交易订单",
["rate"]: "汇率监控",
["rate-list"]: "同步记录",
["rate-syntax"]: "汇率配置",
["system-base"]: "基本设置",
["system-rpc"]: "区块节点",
["create-order"]: "创建订单",
["github-api-doc"]: "对接文档",
["file"]: "文件管理",
["document-library"]: "文件库",
["table"]: "列表管理",
["common-table"]: "普通列表",
["custom-table"]: "自定义列表",
["form"]: "表单管理",
["common-form"]: "普通表单",
["step-form"]: "分步表单",
["multilevel"]: "多级菜单",
["second-1"]: "二级菜单-1",
["second-2"]: "二级菜单-2",
["third-1"]: "三级菜单-1",
["third-2"]: "三级菜单-2",
["third-3"]: "三级菜单-3",
["third-4"]: "三级菜单-4",
["third-5"]: "三级菜单-5",
["third-6"]: "三级菜单-6",
["third-7"]: "三级菜单-7",
["third-8"]: "三级菜单-8",
["third-9"]: "三级菜单-9",
["component"]: "组件管理",
["player"]: "播放器",
["print"]: "打印",
["draggable"]: "拖拽",
["editor"]: "富文本",
["newbie"]: "新手指引",
["icon-selector"]: "图标选择器",
["user-center"]: "用户中心",
["fingerprintjs2"]: "浏览器指纹",
["barcode"]: "条形码",
["qrcode"]: "二维码",
["pinyin"]: "拼音转换",
["markdown"]: "Markdown",
["directive"]: "自定义指令",
["anti-shake"]: "防抖",
["throttle"]: "节流",
["test-directive"]: "测试指令",
["personal"]: "个人中心",
["userinfo"]: "用户信息",
["user-settings"]: "用户设置",
["system"]: "系统管理",
["account"]: "账号管理",
["role"]: "角色管理",
["menu"]: "菜单管理",
["division"]: "部门管理",
["dictionary"]: "字典管理",
["log"]: "系统日志",
["about"]: "关于项目",
["link"]: "外部链接",
["internal"]: "内部",
["uigradients"]: "渐变配色",
["color-taking-tool"]: "取色工具",
["grid-generator"]: "网格生成器",
["external"]: "外部",
["vue"]: "vue官网",
["vite"]: "vite官网",
["github"]: "github",
["SnowAdmin-Docs"]: "SnowAdmin文档",
["juejin"]: "掘金",
["disable-menu"]: "停用菜单",
["hide-menu"]: "隐藏菜单",
["system-monitor"]: "系统监控",
["onlineuser"]: "在线用户",
["crontab"]: "定时任务",
["crontab-logs"]: "任务日志",
["i18n"]: "国际化",
["amap"]: "高德地图",
["permission"]: "权限测试",
["btn-perm"]: "按钮权限",
["admin-page"]: "管理员页面",
["common-page"]: "普通角色页面",
["functions"]: "常用功能",
["routing-operation"]: "路由操作",
["common-route"]: "普通路由",
["dynamic-route"]: "动态路由",
["audio"]: "音频",
["recorder"]: "录音",
["virtual-list"]: "虚拟列表",
["common-tools"]: "常用工具类",
["tree-tools"]: "树处理工具类",
["file-tools"]: "文件工具类",
["verify-tools"]: "校验工具类",
["common-layouts"]: "常用布局",
["data-screen"]: "数据大屏",
["thin-preview"]: "极简版预览",
["test"]: "测试"
}
};
export default {
system: {
["login"]: "登录",
["not-power"]: "没有权限",
["not-found"]: "未找到页面",
["zh-CN"]: "中文",
["en-US"]: "English",
["refresh"]: "刷新",
["close-current"]: "关闭当前",
["close-left-side"]: "关闭左侧",
["close-right-side"]: "关闭右侧",
["close-other"]: "关闭其它",
["close-all"]: "关闭全部",
["switch-to-night-mode"]: "切换黑夜模式",
["switch-to-daytime-mode"]: "切换白天模式",
["full-screen"]: "全屏",
["exit-full-screen"]: "退出全屏",
["system-settings"]: "系统设置",
["theme-settings"]: "主题设置",
["personal-information"]: "个人信息",
["change-password"]: "修改密码",
["project-address"]: "项目地址",
["logout"]: "退出登录",
["notice"]: "通知",
["message"]: "消息",
["backlog"]: "待办",
["switch-language-to-preview"]: "请切换语言来预览国际化效果",
["please-enter-something"]: "请输入"
},
menu: {
["home"]: "首页",
["wallet"]: "钱包管理",
["order"]: "交易订单",
["rate"]: "汇率监控",
["rate-list"]: "同步记录",
["rate-syntax"]: "汇率配置",
["system-base"]: "基本设置",
["system-rpc"]: "区块节点",
["create-order"]: "创建订单",
["github-api-doc"]: "对接文档",
["file"]: "文件管理",
["document-library"]: "文件库",
["table"]: "列表管理",
["common-table"]: "普通列表",
["custom-table"]: "自定义列表",
["form"]: "表单管理",
["common-form"]: "普通表单",
["step-form"]: "分步表单",
["multilevel"]: "多级菜单",
["second-1"]: "二级菜单-1",
["second-2"]: "二级菜单-2",
["third-1"]: "三级菜单-1",
["third-2"]: "三级菜单-2",
["third-3"]: "三级菜单-3",
["third-4"]: "三级菜单-4",
["third-5"]: "三级菜单-5",
["third-6"]: "三级菜单-6",
["third-7"]: "三级菜单-7",
["third-8"]: "三级菜单-8",
["third-9"]: "三级菜单-9",
["component"]: "组件管理",
["player"]: "播放器",
["print"]: "打印",
["draggable"]: "拖拽",
["editor"]: "富文本",
["newbie"]: "新手指引",
["icon-selector"]: "图标选择器",
["user-center"]: "用户中心",
["fingerprintjs2"]: "浏览器指纹",
["barcode"]: "条形码",
["qrcode"]: "二维码",
["pinyin"]: "拼音转换",
["markdown"]: "Markdown",
["directive"]: "自定义指令",
["anti-shake"]: "防抖",
["throttle"]: "节流",
["test-directive"]: "测试指令",
["personal"]: "个人中心",
["userinfo"]: "用户信息",
["user-settings"]: "用户设置",
["system"]: "系统管理",
["account"]: "账号管理",
["role"]: "角色管理",
["menu"]: "菜单管理",
["division"]: "部门管理",
["dictionary"]: "字典管理",
["log"]: "系统日志",
["about"]: "关于项目",
["link"]: "外部链接",
["internal"]: "内部",
["uigradients"]: "渐变配色",
["color-taking-tool"]: "取色工具",
["grid-generator"]: "网格生成器",
["external"]: "外部",
["vue"]: "vue官网",
["vite"]: "vite官网",
["github"]: "github",
["SnowAdmin-Docs"]: "SnowAdmin文档",
["juejin"]: "掘金",
["disable-menu"]: "停用菜单",
["hide-menu"]: "隐藏菜单",
["system-monitor"]: "系统监控",
["onlineuser"]: "在线用户",
["crontab"]: "定时任务",
["crontab-logs"]: "任务日志",
["i18n"]: "国际化",
["amap"]: "高德地图",
["permission"]: "权限测试",
["btn-perm"]: "按钮权限",
["admin-page"]: "管理员页面",
["common-page"]: "普通角色页面",
["functions"]: "常用功能",
["routing-operation"]: "路由操作",
["common-route"]: "普通路由",
["dynamic-route"]: "动态路由",
["audio"]: "音频",
["recorder"]: "录音",
["virtual-list"]: "虚拟列表",
["common-tools"]: "常用工具类",
["tree-tools"]: "树处理工具类",
["file-tools"]: "文件工具类",
["verify-tools"]: "校验工具类",
["common-layouts"]: "常用布局",
["data-screen"]: "数据大屏",
["thin-preview"]: "极简版预览",
["test"]: "测试"
}
};
+75 -75
View File
@@ -1,75 +1,75 @@
<template>
<div :class="asideDark ? 'aside dark' : 'aside'">
<Logo />
<a-layout-sider :collapsed="collapsed" breakpoint="xl" class="layout_side" :width="220">
<a-scrollbar style="height: 100%; overflow: auto" outer-class="scrollbar"><Menu :route-tree="routeTree" /></a-scrollbar>
</a-layout-sider>
</div>
</template>
<script setup lang="ts">
import Logo from "@/layout/components/Logo/index.vue";
import Menu from "@/layout/components/Menu/index.vue";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useRouteConfigStore } from "@/store/modules/route-config";
const themeStore = useThemeConfig();
const { collapsed, asideDark } = storeToRefs(themeStore);
const routerStore = useRouteConfigStore();
const { routeTree } = storeToRefs(routerStore);
</script>
<style lang="scss" scoped>
.aside {
display: flex;
flex-direction: column;
height: 100vh;
}
.dark {
background: #232324;
}
.layout_side {
flex: 1;
overflow: hidden;
.scrollbar {
height: 100%;
}
}
// 修改左侧滚动条宽度
:deep(.arco-scrollbar-thumb-direction-vertical .arco-scrollbar-thumb-bar) {
width: 4px;
margin-left: 8px;
}
// 去掉右侧阴影并替换为边线
:deep(.arco-layout-sider-light) {
border-right: $border-1 solid $color-border-2;
box-shadow: unset;
}
// 解决折叠菜单的icon不居中问题
:deep(.arco-menu-vertical.arco-menu-collapsed) {
// 消除icon的自带padding值,并且让元素居中
.arco-menu-has-icon {
justify-content: center;
padding: 0;
}
// 消除icon的自带margin-right值,并且设置icon的padding值以保留icon空隙
.arco-menu-icon {
padding: 10px 0;
margin-right: 0;
}
// 消除title占位
.arco-menu-title {
display: none;
}
}
// 去掉sider背景
.arco-layout-sider {
background: unset;
}
</style>
<template>
<div :class="asideDark ? 'aside dark' : 'aside'">
<Logo />
<a-layout-sider :collapsed="collapsed" breakpoint="xl" class="layout_side" :width="220">
<a-scrollbar style="height: 100%; overflow: auto" outer-class="scrollbar"><Menu :route-tree="routeTree" /></a-scrollbar>
</a-layout-sider>
</div>
</template>
<script setup lang="ts">
import Logo from "@/layout/components/Logo/index.vue";
import Menu from "@/layout/components/Menu/index.vue";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useRouteConfigStore } from "@/store/modules/route-config";
const themeStore = useThemeConfig();
const { collapsed, asideDark } = storeToRefs(themeStore);
const routerStore = useRouteConfigStore();
const { routeTree } = storeToRefs(routerStore);
</script>
<style lang="scss" scoped>
.aside {
display: flex;
flex-direction: column;
height: 100vh;
}
.dark {
background: #232324;
}
.layout_side {
flex: 1;
overflow: hidden;
.scrollbar {
height: 100%;
}
}
// 修改左侧滚动条宽度
:deep(.arco-scrollbar-thumb-direction-vertical .arco-scrollbar-thumb-bar) {
width: 4px;
margin-left: 8px;
}
// 去掉右侧阴影并替换为边线
:deep(.arco-layout-sider-light) {
border-right: $border-1 solid $color-border-2;
box-shadow: unset;
}
// 解决折叠菜单的icon不居中问题
:deep(.arco-menu-vertical.arco-menu-collapsed) {
// 消除icon的自带padding值,并且让元素居中
.arco-menu-has-icon {
justify-content: center;
padding: 0;
}
// 消除icon的自带margin-right值,并且设置icon的padding值以保留icon空隙
.arco-menu-icon {
padding: 10px 0;
margin-right: 0;
}
// 消除title占位
.arco-menu-title {
display: none;
}
}
// 去掉sider背景
.arco-layout-sider {
background: unset;
}
</style>
@@ -1,81 +1,81 @@
<template>
<div id="system-breadcrumb" class="breadcrumb" v-if="!isMobile && isBreadcrumb">
<a-space direction="vertical">
<a-breadcrumb>
<a-breadcrumb-item v-for="(item, index) in breadcrumb" :key="item.path" :class="transition">
<span v-if="index === breadcrumb.length - 1" class="main_button">{{ $t(`menu.${item?.meta?.title || ""}`) }}</span>
<span v-else class="route_button" @click="onBreadcrumb(item)">{{ $t(`menu.${item?.meta?.title || ""}`) }}</span>
</a-breadcrumb-item>
</a-breadcrumb>
</a-space>
</div>
</template>
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useRouteConfigStore } from "@/store/modules/route-config";
import { useDevicesSize } from "@/hooks/useDevicesSize";
import { findPathOfParentNode } from "@/utils/tree-tools";
import { HOME_PATH } from "@/config/index";
const themeStore = useThemeConfig();
const { isBreadcrumb, transitionPage } = storeToRefs(themeStore);
const routeConfigStore = useRouteConfigStore();
const { routeTree } = storeToRefs(routeConfigStore);
const { isMobile } = useDevicesSize();
const route = useRoute();
const router = useRouter();
/**
* 获取面包屑
* 根据当前路由信息获取,route.matched可以获取当前路由的所有父级路由信息
* 如果当前路由是home路由,则只返回当前路由信息(说明当前就是顶层)
* 否则返回所有父级路由信息,顶层路由重写为首页
*/
const breadcrumb = computed(() => {
// 如果是首页则直接返回当前路由信息
if (route.path === HOME_PATH) return [route];
// 返回路径信息
let list = findPathOfParentNode(routeTree.value, "name", route.name);
if (!list) return [];
if (!routeTree.value[0].children) list.unshift(routeTree.value[0]);
return list;
});
// 页面过渡
const transition = computed(() => {
if (transitionPage.value === "fadeInOut") {
return "fadeInOut-enter-active";
} else if (transitionPage.value === "cardInOut") {
return "cardInOut-enter-active";
} else {
return "fadeOut-enter-active";
}
});
// 面包屑跳转
const onBreadcrumb = (route: any) => {
let path = route.redirect || route.path;
router.replace((path as string) || HOME_PATH);
};
</script>
<style lang="scss" scoped>
.breadcrumb {
margin-left: $margin;
overflow: auto;
.main_button {
color: $color-text-1;
white-space: nowrap;
cursor: pointer;
}
.route_button {
color: $color-text-2;
white-space: nowrap;
cursor: pointer;
&:hover {
color: $color-primary;
}
}
}
</style>
<template>
<div id="system-breadcrumb" class="breadcrumb" v-if="!isMobile && isBreadcrumb">
<a-space direction="vertical">
<a-breadcrumb>
<a-breadcrumb-item v-for="(item, index) in breadcrumb" :key="item.path" :class="transition">
<span v-if="index === breadcrumb.length - 1" class="main_button">{{ $t(`menu.${item?.meta?.title || ""}`) }}</span>
<span v-else class="route_button" @click="onBreadcrumb(item)">{{ $t(`menu.${item?.meta?.title || ""}`) }}</span>
</a-breadcrumb-item>
</a-breadcrumb>
</a-space>
</div>
</template>
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useRouteConfigStore } from "@/store/modules/route-config";
import { useDevicesSize } from "@/hooks/useDevicesSize";
import { findPathOfParentNode } from "@/utils/tree-tools";
import { HOME_PATH } from "@/config/index";
const themeStore = useThemeConfig();
const { isBreadcrumb, transitionPage } = storeToRefs(themeStore);
const routeConfigStore = useRouteConfigStore();
const { routeTree } = storeToRefs(routeConfigStore);
const { isMobile } = useDevicesSize();
const route = useRoute();
const router = useRouter();
/**
* 获取面包屑
* 根据当前路由信息获取,route.matched可以获取当前路由的所有父级路由信息
* 如果当前路由是home路由,则只返回当前路由信息(说明当前就是顶层)
* 否则返回所有父级路由信息,顶层路由重写为首页
*/
const breadcrumb = computed(() => {
// 如果是首页则直接返回当前路由信息
if (route.path === HOME_PATH) return [route];
// 返回路径信息
let list = findPathOfParentNode(routeTree.value, "name", route.name);
if (!list) return [];
if (!routeTree.value[0].children) list.unshift(routeTree.value[0]);
return list;
});
// 页面过渡
const transition = computed(() => {
if (transitionPage.value === "fadeInOut") {
return "fadeInOut-enter-active";
} else if (transitionPage.value === "cardInOut") {
return "cardInOut-enter-active";
} else {
return "fadeOut-enter-active";
}
});
// 面包屑跳转
const onBreadcrumb = (route: any) => {
let path = route.redirect || route.path;
router.replace((path as string) || HOME_PATH);
};
</script>
<style lang="scss" scoped>
.breadcrumb {
margin-left: $margin;
overflow: auto;
.main_button {
color: $color-text-1;
white-space: nowrap;
cursor: pointer;
}
.route_button {
color: $color-text-2;
white-space: nowrap;
cursor: pointer;
&:hover {
color: $color-primary;
}
}
}
</style>
@@ -1,75 +1,75 @@
<template>
<a-tabs :default-active-key="current" :active-key="current" @tab-click="onTab">
<a-tab-pane v-for="item in noticeData" :key="item.id">
<template #title>{{ `${$t(`system.${item.title}`)}(${item.data.length})` }}</template>
<div class="notice" v-for="content in item.data" :key="content.id">
<a-image width="36" height="36" fit="cover" :src="myImage" class="notice_img" />
<div class="content margin-left-text">
<div>
<span class="nickname">{{ content.nickname }}</span>
<span class="time margin-left-text">{{ content.time }}</span>
</div>
<div class="context">{{ content.content }}</div>
</div>
</div>
<a-empty v-if="item.data.length === 0" />
</a-tab-pane>
</a-tabs>
</template>
<script setup lang="ts">
import myImage from "@/assets/img/my-image.jpg";
const data = ref([
{ id: 100, img: "", time: "1分钟前", nickname: "兔子先森", content: "一键三连" },
{ id: 120, img: "", time: "1小时前", nickname: "捷克大力士", content: "与你握手问好" },
{ id: 130, img: "", time: "2小时前", nickname: "forever", content: "you forever" }
]);
const noticeData = ref([
{
id: 1,
title: "notice",
data: data.value
},
{ id: 2, title: "message", data: [] },
{ id: 3, title: "backlog", data: [] }
]);
const current = ref<number>(1);
const onTab = (key: number) => {
current.value = key;
};
</script>
<style lang="scss" scoped>
.notice {
display: flex;
align-items: center;
margin-bottom: $margin;
.notice_img {
width: 36px;
height: 36px;
border-radius: 50%;
}
.content {
width: 200px;
.nickname {
font-size: $font-size-body-3;
color: $color-text-2;
}
.time {
font-size: $font-size-body-1;
color: $color-text-3;
}
.context {
font-size: $font-size-body-3;
}
}
}
.margin-left-text {
margin-left: $margin-text;
}
// 解决tabs宽度异常的bug
:deep(.arco-tabs-content .arco-tabs-content-list) {
display: unset;
}
</style>
<template>
<a-tabs :default-active-key="current" :active-key="current" @tab-click="onTab">
<a-tab-pane v-for="item in noticeData" :key="item.id">
<template #title>{{ `${$t(`system.${item.title}`)}(${item.data.length})` }}</template>
<div class="notice" v-for="content in item.data" :key="content.id">
<a-image width="36" height="36" fit="cover" :src="myImage" class="notice_img" />
<div class="content margin-left-text">
<div>
<span class="nickname">{{ content.nickname }}</span>
<span class="time margin-left-text">{{ content.time }}</span>
</div>
<div class="context">{{ content.content }}</div>
</div>
</div>
<a-empty v-if="item.data.length === 0" />
</a-tab-pane>
</a-tabs>
</template>
<script setup lang="ts">
import myImage from "@/assets/img/my-image.jpg";
const data = ref([
{ id: 100, img: "", time: "1分钟前", nickname: "兔子先森", content: "一键三连" },
{ id: 120, img: "", time: "1小时前", nickname: "捷克大力士", content: "与你握手问好" },
{ id: 130, img: "", time: "2小时前", nickname: "forever", content: "you forever" }
]);
const noticeData = ref([
{
id: 1,
title: "notice",
data: data.value
},
{ id: 2, title: "message", data: [] },
{ id: 3, title: "backlog", data: [] }
]);
const current = ref<number>(1);
const onTab = (key: number) => {
current.value = key;
};
</script>
<style lang="scss" scoped>
.notice {
display: flex;
align-items: center;
margin-bottom: $margin;
.notice_img {
width: 36px;
height: 36px;
border-radius: 50%;
}
.content {
width: 200px;
.nickname {
font-size: $font-size-body-3;
color: $color-text-2;
}
.time {
font-size: $font-size-body-1;
color: $color-text-3;
}
.context {
font-size: $font-size-body-3;
}
}
}
.margin-left-text {
margin-left: $margin-text;
}
// 解决tabs宽度异常的bug
:deep(.arco-tabs-content .arco-tabs-content-list) {
display: unset;
}
</style>
@@ -1,48 +1,48 @@
<template>
<div class="menu_fold">
<a-button size="mini" type="text" class="menu_fold_icon" id="system-collapsed" @click="onCollapsed">
<template #icon>
<icon-menu-fold :size="18" v-if="!collapsed" />
<icon-menu-unfold :size="18" v-if="collapsed" />
</template>
</a-button>
</div>
<DrawerAside v-if="!isPc" />
</template>
<script setup lang="ts">
import DrawerAside from "@/layout/components/drawer-aside/index.vue";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useDevicesSize } from "@/hooks/useDevicesSize";
const themeStore = useThemeConfig();
const { collapsed } = storeToRefs(themeStore);
const { isPc } = useDevicesSize();
// 刷新时,PC窗口展开菜单,移动端收起菜单
collapsed.value = isPc.value ? false : true;
// 折叠
const onCollapsed = () => {
themeStore.setCollapsed(!collapsed.value);
};
// 监听屏幕尺寸变化,PC端自动展开菜单,移动端自动收起
watch(isPc, (newV: boolean) => {
collapsed.value = newV ? false : true;
});
</script>
<style lang="scss" scoped>
.menu_fold {
display: flex;
align-items: center;
justify-content: space-around;
width: 32px;
height: 32px;
.menu_fold_icon {
color: $color-text-1;
border-radius: $radius-box-1;
}
}
</style>
<template>
<div class="menu_fold">
<a-button size="mini" type="text" class="menu_fold_icon" id="system-collapsed" @click="onCollapsed">
<template #icon>
<icon-menu-fold :size="18" v-if="!collapsed" />
<icon-menu-unfold :size="18" v-if="collapsed" />
</template>
</a-button>
</div>
<DrawerAside v-if="!isPc" />
</template>
<script setup lang="ts">
import DrawerAside from "@/layout/components/drawer-aside/index.vue";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useDevicesSize } from "@/hooks/useDevicesSize";
const themeStore = useThemeConfig();
const { collapsed } = storeToRefs(themeStore);
const { isPc } = useDevicesSize();
// 刷新时,PC窗口展开菜单,移动端收起菜单
collapsed.value = isPc.value ? false : true;
// 折叠
const onCollapsed = () => {
themeStore.setCollapsed(!collapsed.value);
};
// 监听屏幕尺寸变化,PC端自动展开菜单,移动端自动收起
watch(isPc, (newV: boolean) => {
collapsed.value = newV ? false : true;
});
</script>
<style lang="scss" scoped>
.menu_fold {
display: flex;
align-items: center;
justify-content: space-around;
width: 32px;
height: 32px;
.menu_fold_icon {
color: $color-text-1;
border-radius: $radius-box-1;
}
}
</style>
@@ -1,19 +1,19 @@
<template>
<div class="header_crumb">
<ButtonCollapsed />
<Breadcrumb />
</div>
</template>
<script setup lang="ts">
import Breadcrumb from "@/layout/components/Header/components/Breadcrumb/index.vue";
import ButtonCollapsed from "@/layout/components/Header/components/button-collapsed/index.vue";
</script>
<style lang="scss" scoped>
.header_crumb {
display: flex;
align-items: center;
width: 100%;
}
</style>
<template>
<div class="header_crumb">
<ButtonCollapsed />
<Breadcrumb />
</div>
</template>
<script setup lang="ts">
import Breadcrumb from "@/layout/components/Header/components/Breadcrumb/index.vue";
import ButtonCollapsed from "@/layout/components/Header/components/button-collapsed/index.vue";
</script>
<style lang="scss" scoped>
.header_crumb {
display: flex;
align-items: center;
width: 100%;
}
</style>
@@ -1,224 +1,224 @@
<template>
<div class="header_setting" :class="isMobile && 'head-absolute-fix'">
<!-- 国际化 -->
<!-- 暂时也是真没精力搞国际化 -->
<!-- <a-dropdown trigger="hover" @select="onLange">
<a-button size="mini" type="text" class="icon_btn" id="system-language">
<template #icon>
<icon-language :size="18" />
</template>
</a-button>
<template #content>
<a-doption :disabled="language === 'zh-CN'">{{ $t(`system.zh-CN`) }}</a-doption>
<a-doption :disabled="language === 'en-US'">{{ $t(`system.en-US`) }}</a-doption>
</template>
</a-dropdown> -->
<!-- 皮肤设置 -->
<a-tooltip :content="$t(`system.system-settings`)">
<a-button size="mini" type="text" class="icon_btn" id="system-settings" @click="onSystemSetting">
<template #icon>
<icon-skin :size="18" />
</template>
</a-button>
</a-tooltip>
<!-- 切换黑夜模式 -->
<a-tooltip :content="$t(`system.${!darkMode ? 'switch-to-night-mode' : 'switch-to-daytime-mode'}`)">
<a-button size="mini" type="text" class="icon_btn" id="system-dark" @click="onNightMode">
<template #icon>
<icon-sun-fill :size="18" v-if="!darkMode" />
<icon-moon-fill :size="18" v-else />
</template>
</a-button>
</a-tooltip>
<!-- 我的 -->
<a-dropdown trigger="hover">
<div class="my_setting" id="system-my-setting">
<!-- <a-image width="32" height="32" fit="cover" :src="account.user.avatar || myImage" class="my_image" /> -->
<span class="user-nickname">Hi {{ admin_username || "BEpusdt" }}</span>
<div class="icon_down">
<icon-down style="stroke-width: 3" />
</div>
</div>
<template #content>
<!-- 项目地址 -->
<a-doption @click="onProject">
<template #default>
<s-svg-icon :name="'github'" :size="18" />
<span class="margin-left-text">{{ $t(`system.project-address`) }}</span>
</template>
</a-doption>
<a-divider margin="0" />
<!-- 退出登录 -->
<a-doption @click="logOut">
<template #default>
<s-svg-icon :name="'exit'" :size="18" />
<span class="margin-left-text">{{ $t(`system.logout`) }}</span>
</template>
</a-doption>
</template>
</a-dropdown>
</div>
<SystemSettings :system-open="systemOpen" @system-cancel="systemOpen = false" />
<ThemeSettings :theme-open="themeOpen" @theme-cancel="themeOpen = false" />
</template>
<script setup lang="ts">
// import Notice from "@/layout/components/Header/components/Notice/index.vue";
import SystemSettings from "@/layout/components/Header/components/system-settings/index.vue";
import ThemeSettings from "@/layout/components/Header/components/theme-settings/index.vue";
// import { useI18n } from "vue-i18n";
import { Modal } from "@arco-design/web-vue";
import { useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import { useUserInfoStore } from "@/store/modules/user-info";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useThemeMethods } from "@/hooks/useThemeMethods";
import { useDevicesSize } from "@/hooks/useDevicesSize";
import { useRouteConfigStore } from "@/store/modules/route-config";
// const i18n = useI18n();
const router = useRouter();
const { isMobile } = useDevicesSize();
const userStore = useUserInfoStore();
const themeStore = useThemeConfig();
// const { language, darkMode } = storeToRefs(themeStore);
const { darkMode } = storeToRefs(themeStore);
const { admin_username } = storeToRefs(userStore); // 添加这行来获取 admin_username
// 系统设置
const systemOpen = ref(false);
const onSystemSetting = () => {
systemOpen.value = true;
};
// 主题设置
const themeOpen = ref(false);
// const onThemeSetting = () => {
// themeOpen.value = true;
// };
// 全屏
// const fullScreen = ref(true);
// const onFullScreen = () => {
// if (!document.fullscreenElement) {
// document.documentElement.requestFullscreen();
// fullScreen.value = false;
// } else {
// if (document.exitFullscreen) {
// document.exitFullscreen();
// fullScreen.value = true;
// }
// }
// };
// 黑暗模式
const onNightMode = () => {
darkMode.value = !darkMode.value;
let { setDarkMode } = useThemeMethods();
setDarkMode();
};
// 语言
// const onLange = (value: string) => {
// if (value === "Chinese" || value === "中文") {
// themeStore.setLanguage("zh-CN");
// } else {
// themeStore.setLanguage("en-US");
// }
// i18n.locale.value = language.value;
// };
// 项目地址
const onProject = () => {
window.open("https://github.com/v03413/BEpusdt", "_blank");
};
// 退出登录
const logOut = () => {
Modal.warning({
title: "提示",
content: "确定退出登录?",
hideCancel: false,
closable: true,
onBeforeOk: async () => {
try {
// 用户退出
await userStore.logOut();
router.replace("/login");
// 清除路由数据
useRouteConfigStore().resetRoute();
return true;
} catch {
return false;
}
}
});
};
</script>
<style lang="scss" scoped>
.head-absolute-fix {
position: absolute;
top: 0;
right: $padding;
}
.header_setting {
display: flex;
align-items: center;
justify-content: space-between;
height: 100%;
background-color: $color-bg-2;
> .icon_btn {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-around;
width: $icon-box;
height: $icon-box;
margin-left: $margin;
color: $color-text-1;
border-radius: $radius-box-1;
}
.my_setting {
display: flex;
align-items: center;
justify-content: space-between;
height: 32px;
margin-left: $margin;
overflow: hidden;
.my_image {
margin-right: 8px;
border-radius: 50%;
}
.user-nickname {
white-space: nowrap;
}
.icon_down {
margin: 0 0 0 5px;
transform: rotate(0deg);
transition: transform 0.2s;
}
}
}
.notice {
position: relative;
&::before {
position: absolute;
top: -4px;
right: -2px;
width: 6px;
height: 6px;
content: "";
background: $color-danger;
border: 2px solid #ffffff;
border-radius: 50%;
}
}
:deep(.arco-dropdown-open) {
.icon_down {
transform: rotate(180deg) !important;
}
}
.margin-left-text {
margin-left: $margin-text;
}
</style>
<template>
<div class="header_setting" :class="isMobile && 'head-absolute-fix'">
<!-- 国际化 -->
<!-- 暂时也是真没精力搞国际化 -->
<!-- <a-dropdown trigger="hover" @select="onLange">
<a-button size="mini" type="text" class="icon_btn" id="system-language">
<template #icon>
<icon-language :size="18" />
</template>
</a-button>
<template #content>
<a-doption :disabled="language === 'zh-CN'">{{ $t(`system.zh-CN`) }}</a-doption>
<a-doption :disabled="language === 'en-US'">{{ $t(`system.en-US`) }}</a-doption>
</template>
</a-dropdown> -->
<!-- 皮肤设置 -->
<a-tooltip :content="$t(`system.system-settings`)">
<a-button size="mini" type="text" class="icon_btn" id="system-settings" @click="onSystemSetting">
<template #icon>
<icon-skin :size="18" />
</template>
</a-button>
</a-tooltip>
<!-- 切换黑夜模式 -->
<a-tooltip :content="$t(`system.${!darkMode ? 'switch-to-night-mode' : 'switch-to-daytime-mode'}`)">
<a-button size="mini" type="text" class="icon_btn" id="system-dark" @click="onNightMode">
<template #icon>
<icon-sun-fill :size="18" v-if="!darkMode" />
<icon-moon-fill :size="18" v-else />
</template>
</a-button>
</a-tooltip>
<!-- 我的 -->
<a-dropdown trigger="hover">
<div class="my_setting" id="system-my-setting">
<!-- <a-image width="32" height="32" fit="cover" :src="account.user.avatar || myImage" class="my_image" /> -->
<span class="user-nickname">Hi {{ admin_username || "BEpusdt" }}</span>
<div class="icon_down">
<icon-down style="stroke-width: 3" />
</div>
</div>
<template #content>
<!-- 项目地址 -->
<a-doption @click="onProject">
<template #default>
<s-svg-icon :name="'github'" :size="18" />
<span class="margin-left-text">{{ $t(`system.project-address`) }}</span>
</template>
</a-doption>
<a-divider margin="0" />
<!-- 退出登录 -->
<a-doption @click="logOut">
<template #default>
<s-svg-icon :name="'exit'" :size="18" />
<span class="margin-left-text">{{ $t(`system.logout`) }}</span>
</template>
</a-doption>
</template>
</a-dropdown>
</div>
<SystemSettings :system-open="systemOpen" @system-cancel="systemOpen = false" />
<ThemeSettings :theme-open="themeOpen" @theme-cancel="themeOpen = false" />
</template>
<script setup lang="ts">
// import Notice from "@/layout/components/Header/components/Notice/index.vue";
import SystemSettings from "@/layout/components/Header/components/system-settings/index.vue";
import ThemeSettings from "@/layout/components/Header/components/theme-settings/index.vue";
// import { useI18n } from "vue-i18n";
import { Modal } from "@arco-design/web-vue";
import { useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import { useUserInfoStore } from "@/store/modules/user-info";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useThemeMethods } from "@/hooks/useThemeMethods";
import { useDevicesSize } from "@/hooks/useDevicesSize";
import { useRouteConfigStore } from "@/store/modules/route-config";
// const i18n = useI18n();
const router = useRouter();
const { isMobile } = useDevicesSize();
const userStore = useUserInfoStore();
const themeStore = useThemeConfig();
// const { language, darkMode } = storeToRefs(themeStore);
const { darkMode } = storeToRefs(themeStore);
const { admin_username } = storeToRefs(userStore); // 添加这行来获取 admin_username
// 系统设置
const systemOpen = ref(false);
const onSystemSetting = () => {
systemOpen.value = true;
};
// 主题设置
const themeOpen = ref(false);
// const onThemeSetting = () => {
// themeOpen.value = true;
// };
// 全屏
// const fullScreen = ref(true);
// const onFullScreen = () => {
// if (!document.fullscreenElement) {
// document.documentElement.requestFullscreen();
// fullScreen.value = false;
// } else {
// if (document.exitFullscreen) {
// document.exitFullscreen();
// fullScreen.value = true;
// }
// }
// };
// 黑暗模式
const onNightMode = () => {
darkMode.value = !darkMode.value;
let { setDarkMode } = useThemeMethods();
setDarkMode();
};
// 语言
// const onLange = (value: string) => {
// if (value === "Chinese" || value === "中文") {
// themeStore.setLanguage("zh-CN");
// } else {
// themeStore.setLanguage("en-US");
// }
// i18n.locale.value = language.value;
// };
// 项目地址
const onProject = () => {
window.open("https://github.com/v03413/BEpusdt", "_blank");
};
// 退出登录
const logOut = () => {
Modal.warning({
title: "提示",
content: "确定退出登录?",
hideCancel: false,
closable: true,
onBeforeOk: async () => {
try {
// 用户退出
await userStore.logOut();
router.replace("/login");
// 清除路由数据
useRouteConfigStore().resetRoute();
return true;
} catch {
return false;
}
}
});
};
</script>
<style lang="scss" scoped>
.head-absolute-fix {
position: absolute;
top: 0;
right: $padding;
}
.header_setting {
display: flex;
align-items: center;
justify-content: space-between;
height: 100%;
background-color: $color-bg-2;
> .icon_btn {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-around;
width: $icon-box;
height: $icon-box;
margin-left: $margin;
color: $color-text-1;
border-radius: $radius-box-1;
}
.my_setting {
display: flex;
align-items: center;
justify-content: space-between;
height: 32px;
margin-left: $margin;
overflow: hidden;
.my_image {
margin-right: 8px;
border-radius: 50%;
}
.user-nickname {
white-space: nowrap;
}
.icon_down {
margin: 0 0 0 5px;
transform: rotate(0deg);
transition: transform 0.2s;
}
}
}
.notice {
position: relative;
&::before {
position: absolute;
top: -4px;
right: -2px;
width: 6px;
height: 6px;
content: "";
background: $color-danger;
border: 2px solid #ffffff;
border-radius: 50%;
}
}
:deep(.arco-dropdown-open) {
.icon_down {
transform: rotate(180deg) !important;
}
}
.margin-left-text {
margin-left: $margin-text;
}
</style>
@@ -1,154 +1,154 @@
<template>
<a-drawer :width="340" :visible="props.systemOpen" @ok="handleCancel" @cancel="handleCancel" unmount-on-close>
<template #title> 系统设置 </template>
<div>
<div>
<div class="title">界面设置</div>
<div class="flex-row">
<div>菜单折叠</div>
<a-switch v-model="collapsed" />
</div>
<div class="flex-row">
<div>菜单手风琴</div>
<a-switch v-model="isAccordion" />
</div>
<div class="flex-row">
<div>面包屑</div>
<a-switch v-model="isBreadcrumb" />
</div>
<div class="flex-row">
<div>标签栏</div>
<a-switch v-model="isTabs" @change="tabsChange" />
</div>
<div class="flex-row">
<div>页脚</div>
<a-switch v-model="isFooter" />
</div>
</div>
<div>
<div class="title">水印设置</div>
<div class="flex-row">
<div>水印颜色</div>
<pick-colors
:theme="darkMode ? 'dark' : 'light'"
show-alpha
format="rgb"
v-model:value="watermarkStyle.color"
:colors="['rgba(0, 0, 0, 0.15)']"
:z-index="2000"
/>
</div>
<div class="flex-row">
<div>水印文案</div>
<a-input :style="{ width: '100px' }" v-model="watermark" placeholder="请输入" allow-clear />
</div>
<div class="flex-row">
<div>水印大小</div>
<a-slider v-model="watermarkStyle.fontSize" :min="10" :max="50" :style="{ width: '100px' }" />
</div>
<div class="flex-row">
<div>水印角度</div>
<a-slider v-model="watermarkRotate" :min="0" :max="360" :style="{ width: '100px' }" />
</div>
<div class="flex-row">
<div>水印间隙</div>
<a-slider :default-value="gapInfo[0]" :min="0" :max="300" :style="{ width: '100px' }" @change="onWatermarkGap" />
</div>
</div>
<div>
<div class="title">系统设置</div>
<div class="flex-row">
<div>防调试</div>
<a-switch v-model="debugPrevention" />
</div>
</div>
</div>
</a-drawer>
</template>
<script setup lang="ts">
import PickColors from "vue-pick-colors";
import { storeToRefs } from "pinia";
import { useRouteConfigStore } from "@/store/modules/route-config";
import { useThemeConfig } from "@/store/modules/theme-config";
import { currentlyRoute } from "@/router/route-output";
import { DebugControl } from "@/utils/debug-prevention";
const themeStore = useThemeConfig();
const routerStore = useRouteConfigStore();
const {
collapsed,
isAccordion,
isBreadcrumb,
isTabs,
isFooter,
watermark,
watermarkStyle,
watermarkRotate,
watermarkGap,
darkMode,
debugPrevention
} = storeToRefs(themeStore);
const { tabsList, cacheRoutes } = storeToRefs(routerStore);
const route = useRoute();
const props = defineProps({
systemOpen: {
type: Boolean,
default: false
}
});
const gapInfo = ref(watermarkGap.value);
const onWatermarkGap = (e: number) => {
watermarkGap.value = watermarkGap.value.map(() => e);
};
/*
是否关闭tabs栏
如果关闭,那么所有tabs全部取消、所有页面缓存全部取消
如果开启,那么添加当前路由到tabs
*/
const tabsChange = (e: boolean) => {
if (!e) {
tabsList.value = [];
cacheRoutes.value = [];
} else {
currentlyRoute(route);
}
};
// 监听debug开关;
const debugControl = new DebugControl();
watch(
() => debugPrevention.value,
newValue => {
if (newValue) {
debugControl.start();
} else {
debugControl.stop();
}
},
{
immediate: true
}
);
const emits = defineEmits(["systemCancel"]);
const handleCancel = () => {
emits("systemCancel");
};
</script>
<style lang="scss" scoped>
.title {
margin-bottom: $margin;
font-size: $font-size-title-1;
font-weight: bold;
color: $color-text-1;
}
.flex-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: $margin;
}
</style>
<template>
<a-drawer :width="340" :visible="props.systemOpen" @ok="handleCancel" @cancel="handleCancel" unmount-on-close>
<template #title> 系统设置 </template>
<div>
<div>
<div class="title">界面设置</div>
<div class="flex-row">
<div>菜单折叠</div>
<a-switch v-model="collapsed" />
</div>
<div class="flex-row">
<div>菜单手风琴</div>
<a-switch v-model="isAccordion" />
</div>
<div class="flex-row">
<div>面包屑</div>
<a-switch v-model="isBreadcrumb" />
</div>
<div class="flex-row">
<div>标签栏</div>
<a-switch v-model="isTabs" @change="tabsChange" />
</div>
<div class="flex-row">
<div>页脚</div>
<a-switch v-model="isFooter" />
</div>
</div>
<div>
<div class="title">水印设置</div>
<div class="flex-row">
<div>水印颜色</div>
<pick-colors
:theme="darkMode ? 'dark' : 'light'"
show-alpha
format="rgb"
v-model:value="watermarkStyle.color"
:colors="['rgba(0, 0, 0, 0.15)']"
:z-index="2000"
/>
</div>
<div class="flex-row">
<div>水印文案</div>
<a-input :style="{ width: '100px' }" v-model="watermark" placeholder="请输入" allow-clear />
</div>
<div class="flex-row">
<div>水印大小</div>
<a-slider v-model="watermarkStyle.fontSize" :min="10" :max="50" :style="{ width: '100px' }" />
</div>
<div class="flex-row">
<div>水印角度</div>
<a-slider v-model="watermarkRotate" :min="0" :max="360" :style="{ width: '100px' }" />
</div>
<div class="flex-row">
<div>水印间隙</div>
<a-slider :default-value="gapInfo[0]" :min="0" :max="300" :style="{ width: '100px' }" @change="onWatermarkGap" />
</div>
</div>
<div>
<div class="title">系统设置</div>
<div class="flex-row">
<div>防调试</div>
<a-switch v-model="debugPrevention" />
</div>
</div>
</div>
</a-drawer>
</template>
<script setup lang="ts">
import PickColors from "vue-pick-colors";
import { storeToRefs } from "pinia";
import { useRouteConfigStore } from "@/store/modules/route-config";
import { useThemeConfig } from "@/store/modules/theme-config";
import { currentlyRoute } from "@/router/route-output";
import { DebugControl } from "@/utils/debug-prevention";
const themeStore = useThemeConfig();
const routerStore = useRouteConfigStore();
const {
collapsed,
isAccordion,
isBreadcrumb,
isTabs,
isFooter,
watermark,
watermarkStyle,
watermarkRotate,
watermarkGap,
darkMode,
debugPrevention
} = storeToRefs(themeStore);
const { tabsList, cacheRoutes } = storeToRefs(routerStore);
const route = useRoute();
const props = defineProps({
systemOpen: {
type: Boolean,
default: false
}
});
const gapInfo = ref(watermarkGap.value);
const onWatermarkGap = (e: number) => {
watermarkGap.value = watermarkGap.value.map(() => e);
};
/*
是否关闭tabs栏
如果关闭,那么所有tabs全部取消、所有页面缓存全部取消
如果开启,那么添加当前路由到tabs
*/
const tabsChange = (e: boolean) => {
if (!e) {
tabsList.value = [];
cacheRoutes.value = [];
} else {
currentlyRoute(route);
}
};
// 监听debug开关;
const debugControl = new DebugControl();
watch(
() => debugPrevention.value,
newValue => {
if (newValue) {
debugControl.start();
} else {
debugControl.stop();
}
},
{
immediate: true
}
);
const emits = defineEmits(["systemCancel"]);
const handleCancel = () => {
emits("systemCancel");
};
</script>
<style lang="scss" scoped>
.title {
margin-bottom: $margin;
font-size: $font-size-title-1;
font-weight: bold;
color: $color-text-1;
}
.flex-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: $margin;
}
</style>
@@ -1,237 +1,237 @@
<template>
<a-drawer :width="340" :visible="props.themeOpen" @ok="handleCancel" @cancel="handleCancel" unmount-on-close>
<template #title> 主题设置 </template>
<div>
<div>
<a-divider orientation="center">导航模式</a-divider>
<div class="flex-center">
<a-tooltip v-for="item in layoutList" :key="item.value" :content="item.label" position="top" mini>
<div
:class="layoutType === item.value ? `current-layout ${item.class}` : item.class"
@click="layouetChange(item.value)"
>
<icon-check-circle-fill class="layout-icon" />
</div>
</a-tooltip>
</div>
</div>
<div class="box-gap">
<a-divider orientation="center">主题设置</a-divider>
<div class="flex-center">
<ColorPicker
:theme="darkMode ? 'dark' : 'light'"
sucker-hide
:colors-default="presetColors"
:color="themeColor"
@change-color="themeColorChange"
/>
</div>
</div>
<div class="box-gap">
<div class="flex-row">
<div>色弱模式</div>
<a-switch v-model="colorWeakMode" @change="onColorWeak" />
</div>
<div class="flex-row">
<div>灰色模式</div>
<a-switch v-model="grayMode" @change="onGray" />
</div>
<div class="flex-row">
<div>侧边栏深色</div>
<a-switch :disabled="darkMode" v-model="asideDark" />
</div>
<div class="flex-row">
<div>页面过渡</div>
<a-select v-model="transitionPage" :style="{ width: '120px' }" placeholder="请选择">
<a-option v-for="item in transitions" :key="item.value" :value="item.value" :label="item.label" />
</a-select>
</div>
</div>
</div>
</a-drawer>
</template>
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useThemeMethods } from "@/hooks/useThemeMethods";
import { useDevicesSize } from "@/hooks/useDevicesSize";
import { ColorPicker } from "vue-color-kit";
import "vue-color-kit/dist/vue-color-kit.css";
const themeStore = useThemeConfig();
const { layoutType, collapsed, colorWeakMode, grayMode, darkMode, asideDark, transitionPage, themeColor, presetColors } =
storeToRefs(themeStore);
const layoutList = reactive({
layoutDefaults: {
value: "layoutDefaults",
label: "默认布局",
class: "layout-defaults"
},
layoutHead: {
value: "layoutHead",
label: "横向布局",
class: "layout-head"
},
layoutMixing: {
value: "layoutMixing",
label: "混合布局",
class: "layout-mixing"
}
});
const transitions = ref([
{ value: "fadeInOut", label: "轻过渡" },
{ value: "cardInOut", label: "卡片" },
{ value: "fadeOut", label: "渐退" }
]);
interface IThemeColor {
hex: string;
hsv: {
h: number;
s: number;
v: number;
};
rgba: {
r: number;
g: number;
b: number;
a: number;
};
}
// 主题色设置
const themeColorChange = (value: IThemeColor) => {
themeColor.value = value.hex;
const { setThemeColor } = useThemeMethods();
setThemeColor();
};
// 色弱模式
const onColorWeak = () => {
const { setColorWeak } = useThemeMethods();
setColorWeak();
};
// 灰色模式
const onGray = () => {
const { setGray } = useThemeMethods();
setGray();
};
// 布局变化
const layouetChange = (type: string) => {
layoutType.value = type;
const { isPc } = useDevicesSize();
collapsed.value = isPc.value ? false : true;
};
const props = defineProps({
themeOpen: {
type: Boolean,
default: false
}
});
const emits = defineEmits(["themeCancel"]);
const handleCancel = () => {
emits("themeCancel");
};
</script>
<style lang="scss" scoped>
.box-gap {
margin-top: 30px;
}
.flex-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: $margin;
}
.flex-center {
display: flex;
column-gap: $margin;
align-items: center;
justify-content: center;
margin-bottom: $margin;
}
.layout-defaults,
.layout-head,
.layout-mixing {
width: 70px;
height: 50px;
overflow: hidden;
background: $color-fill-1;
border-radius: $radius-box-1;
box-shadow: $shadow-special;
.layout-icon {
display: none;
}
}
.current-layout {
position: relative;
.layout-icon {
position: absolute;
right: 2px;
bottom: 2px;
display: block;
font-size: $font-size-body-3;
color: $color-primary;
}
}
.layout-defaults {
position: relative;
&::before {
position: absolute;
left: 0;
width: 10px;
height: 100%;
content: "";
background: #232324;
}
&::after {
position: absolute;
top: 0;
right: 0;
width: 60px;
height: 10px;
content: "";
background: #c2c4c8;
}
}
.layout-head {
position: relative;
&::before {
position: absolute;
top: 0;
width: 100%;
height: 10px;
content: "";
background: #232324;
}
}
.layout-mixing {
position: relative;
&::before {
position: absolute;
top: 0;
width: 100%;
height: 10px;
content: "";
background: #232324;
}
&::after {
position: absolute;
top: 10px;
left: 0;
width: 10px;
height: calc(100% - 10px);
content: "";
background: #232324;
}
}
:deep(.arco-divider-text) {
background: $color-bg-3;
}
</style>
<template>
<a-drawer :width="340" :visible="props.themeOpen" @ok="handleCancel" @cancel="handleCancel" unmount-on-close>
<template #title> 主题设置 </template>
<div>
<div>
<a-divider orientation="center">导航模式</a-divider>
<div class="flex-center">
<a-tooltip v-for="item in layoutList" :key="item.value" :content="item.label" position="top" mini>
<div
:class="layoutType === item.value ? `current-layout ${item.class}` : item.class"
@click="layouetChange(item.value)"
>
<icon-check-circle-fill class="layout-icon" />
</div>
</a-tooltip>
</div>
</div>
<div class="box-gap">
<a-divider orientation="center">主题设置</a-divider>
<div class="flex-center">
<ColorPicker
:theme="darkMode ? 'dark' : 'light'"
sucker-hide
:colors-default="presetColors"
:color="themeColor"
@change-color="themeColorChange"
/>
</div>
</div>
<div class="box-gap">
<div class="flex-row">
<div>色弱模式</div>
<a-switch v-model="colorWeakMode" @change="onColorWeak" />
</div>
<div class="flex-row">
<div>灰色模式</div>
<a-switch v-model="grayMode" @change="onGray" />
</div>
<div class="flex-row">
<div>侧边栏深色</div>
<a-switch :disabled="darkMode" v-model="asideDark" />
</div>
<div class="flex-row">
<div>页面过渡</div>
<a-select v-model="transitionPage" :style="{ width: '120px' }" placeholder="请选择">
<a-option v-for="item in transitions" :key="item.value" :value="item.value" :label="item.label" />
</a-select>
</div>
</div>
</div>
</a-drawer>
</template>
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useThemeMethods } from "@/hooks/useThemeMethods";
import { useDevicesSize } from "@/hooks/useDevicesSize";
import { ColorPicker } from "vue-color-kit";
import "vue-color-kit/dist/vue-color-kit.css";
const themeStore = useThemeConfig();
const { layoutType, collapsed, colorWeakMode, grayMode, darkMode, asideDark, transitionPage, themeColor, presetColors } =
storeToRefs(themeStore);
const layoutList = reactive({
layoutDefaults: {
value: "layoutDefaults",
label: "默认布局",
class: "layout-defaults"
},
layoutHead: {
value: "layoutHead",
label: "横向布局",
class: "layout-head"
},
layoutMixing: {
value: "layoutMixing",
label: "混合布局",
class: "layout-mixing"
}
});
const transitions = ref([
{ value: "fadeInOut", label: "轻过渡" },
{ value: "cardInOut", label: "卡片" },
{ value: "fadeOut", label: "渐退" }
]);
interface IThemeColor {
hex: string;
hsv: {
h: number;
s: number;
v: number;
};
rgba: {
r: number;
g: number;
b: number;
a: number;
};
}
// 主题色设置
const themeColorChange = (value: IThemeColor) => {
themeColor.value = value.hex;
const { setThemeColor } = useThemeMethods();
setThemeColor();
};
// 色弱模式
const onColorWeak = () => {
const { setColorWeak } = useThemeMethods();
setColorWeak();
};
// 灰色模式
const onGray = () => {
const { setGray } = useThemeMethods();
setGray();
};
// 布局变化
const layouetChange = (type: string) => {
layoutType.value = type;
const { isPc } = useDevicesSize();
collapsed.value = isPc.value ? false : true;
};
const props = defineProps({
themeOpen: {
type: Boolean,
default: false
}
});
const emits = defineEmits(["themeCancel"]);
const handleCancel = () => {
emits("themeCancel");
};
</script>
<style lang="scss" scoped>
.box-gap {
margin-top: 30px;
}
.flex-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: $margin;
}
.flex-center {
display: flex;
column-gap: $margin;
align-items: center;
justify-content: center;
margin-bottom: $margin;
}
.layout-defaults,
.layout-head,
.layout-mixing {
width: 70px;
height: 50px;
overflow: hidden;
background: $color-fill-1;
border-radius: $radius-box-1;
box-shadow: $shadow-special;
.layout-icon {
display: none;
}
}
.current-layout {
position: relative;
.layout-icon {
position: absolute;
right: 2px;
bottom: 2px;
display: block;
font-size: $font-size-body-3;
color: $color-primary;
}
}
.layout-defaults {
position: relative;
&::before {
position: absolute;
left: 0;
width: 10px;
height: 100%;
content: "";
background: #232324;
}
&::after {
position: absolute;
top: 0;
right: 0;
width: 60px;
height: 10px;
content: "";
background: #c2c4c8;
}
}
.layout-head {
position: relative;
&::before {
position: absolute;
top: 0;
width: 100%;
height: 10px;
content: "";
background: #232324;
}
}
.layout-mixing {
position: relative;
&::before {
position: absolute;
top: 0;
width: 100%;
height: 10px;
content: "";
background: #232324;
}
&::after {
position: absolute;
top: 10px;
left: 0;
width: 10px;
height: calc(100% - 10px);
content: "";
background: #232324;
}
}
:deep(.arco-divider-text) {
background: $color-bg-3;
}
</style>
+22 -22
View File
@@ -1,22 +1,22 @@
<template>
<a-layout-header class="header">
<HeaderLeft />
<HeaderRight />
</a-layout-header>
</template>
<script setup lang="ts">
import HeaderLeft from "@/layout/components/Header/components/header-left/index.vue";
import HeaderRight from "@/layout/components/Header/components/header-right/index.vue";
</script>
<style lang="scss" scoped>
.header {
position: relative;
box-sizing: border-box;
display: flex;
align-items: center;
height: 60px;
padding: 0 $padding;
border-bottom: $border-1 solid $color-border-2;
}
</style>
<template>
<a-layout-header class="header">
<HeaderLeft />
<HeaderRight />
</a-layout-header>
</template>
<script setup lang="ts">
import HeaderLeft from "@/layout/components/Header/components/header-left/index.vue";
import HeaderRight from "@/layout/components/Header/components/header-right/index.vue";
</script>
<style lang="scss" scoped>
.header {
position: relative;
box-sizing: border-box;
display: flex;
align-items: center;
height: 60px;
padding: 0 $padding;
border-bottom: $border-1 solid $color-border-2;
}
</style>
+78 -78
View File
@@ -1,78 +1,78 @@
<template>
<div :class="layoutType == 'layoutHead' ? 'logo_head no-border' : 'logo_head'">
<div class="logo_box" :class="(collapsed || layoutType == 'layoutHead') && 'padding-unset'">
<s-svg-icon name="snow" :size="30" />
<span :class="isDark ? 'logo_title dark' : 'logo_title'" v-if="isTitle">{{ title }}</span>
</div>
</div>
</template>
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
const themeStore = useThemeConfig();
const { collapsed, asideDark, layoutType } = storeToRefs(themeStore);
// 全局title
const title = import.meta.env.VITE_GLOB_APP_TITLE;
// 黑暗模式的文字渲染
const isDark = computed(() => {
if (asideDark.value && layoutType.value != "layoutHead") {
return true;
} else {
return false;
}
});
// 是否展示标题
const isTitle = computed(() => {
if (!collapsed.value || layoutType.value == "layoutHead") {
return true;
} else {
return false;
}
});
</script>
<style lang="scss" scoped>
// 头部
.logo_head {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-around;
height: 60px;
border-right: $border-1 solid $color-border-2;
.logo_box {
display: flex;
column-gap: $padding;
align-items: center;
width: 100%;
padding: 0 $padding;
overflow: hidden;
}
// 折叠或者是横向布局-去掉padding,logo居中
.padding-unset {
justify-content: space-around;
padding: unset;
}
.logo_title {
box-sizing: border-box;
max-width: 140px;
overflow: hidden;
text-overflow: ellipsis;
font-size: $font-size-title-2;
font-weight: bold;
text-align: left;
white-space: nowrap;
}
.dark {
color: #ffffff;
}
}
.no-border {
border: unset;
}
</style>
<template>
<div :class="layoutType == 'layoutHead' ? 'logo_head no-border' : 'logo_head'">
<div class="logo_box" :class="(collapsed || layoutType == 'layoutHead') && 'padding-unset'">
<s-svg-icon name="snow" :size="30" />
<span :class="isDark ? 'logo_title dark' : 'logo_title'" v-if="isTitle">{{ title }}</span>
</div>
</div>
</template>
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
const themeStore = useThemeConfig();
const { collapsed, asideDark, layoutType } = storeToRefs(themeStore);
// 全局title
const title = import.meta.env.VITE_GLOB_APP_TITLE;
// 黑暗模式的文字渲染
const isDark = computed(() => {
if (asideDark.value && layoutType.value != "layoutHead") {
return true;
} else {
return false;
}
});
// 是否展示标题
const isTitle = computed(() => {
if (!collapsed.value || layoutType.value == "layoutHead") {
return true;
} else {
return false;
}
});
</script>
<style lang="scss" scoped>
// 头部
.logo_head {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-around;
height: 60px;
border-right: $border-1 solid $color-border-2;
.logo_box {
display: flex;
column-gap: $padding;
align-items: center;
width: 100%;
padding: 0 $padding;
overflow: hidden;
}
// 折叠或者是横向布局-去掉padding,logo居中
.padding-unset {
justify-content: space-around;
padding: unset;
}
.logo_title {
box-sizing: border-box;
max-width: 140px;
overflow: hidden;
text-overflow: ellipsis;
font-size: $font-size-title-2;
font-weight: bold;
text-align: left;
white-space: nowrap;
}
.dark {
color: #ffffff;
}
}
.no-border {
border: unset;
}
</style>
+53 -53
View File
@@ -1,53 +1,53 @@
<template>
<a-menu
:breakpoint="layoutType != 'layoutHead' ? 'xl' : undefined"
:mode="'vertical'"
:theme="asideDark ? 'dark' : 'light'"
:collapsed="collapsed"
:auto-scroll-into-view="true"
:auto-open-selected="true"
:accordion="isAccordion"
:selected-keys="[selectedMenu]"
@menu-item-click="onMenuItem"
>
<MenuItem :route-tree="props.routeTree" />
</a-menu>
</template>
<script setup lang="ts">
import MenuItem from "@/layout/components/Menu/menu-item.vue";
import { useRoutingMethod } from "@/hooks/useRoutingMethod";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
const route = useRoute();
const router = useRouter();
const themeStore = useThemeConfig();
const { collapsed, isAccordion, layoutType, asideDark } = storeToRefs(themeStore);
interface Props {
routeTree: Menu.MenuOptions[];
}
// props的数据类型
// type类型参考:https://cn.vuejs.org/guide/typescript/composition-api.html#typing-component-props
const props = withDefaults(defineProps<Props>(), {
routeTree: () => []
});
const onMenuItem = (path: string) => router.push(path);
const selectedMenu = computed(() => {
const { getAllParentRoute } = useRoutingMethod();
const find = getAllParentRoute(route.matched.at(-1).path);
if (!find) return "";
let path = "";
for (let i = find.length - 1; i >= 0; i--) {
if (find[i].meta && !find[i].meta.hide) {
path = find[i].path;
break;
}
}
return path;
});
</script>
<style lang="scss" scoped></style>
<template>
<a-menu
:breakpoint="layoutType != 'layoutHead' ? 'xl' : undefined"
:mode="'vertical'"
:theme="asideDark ? 'dark' : 'light'"
:collapsed="collapsed"
:auto-scroll-into-view="true"
:auto-open-selected="true"
:accordion="isAccordion"
:selected-keys="[selectedMenu]"
@menu-item-click="onMenuItem"
>
<MenuItem :route-tree="props.routeTree" />
</a-menu>
</template>
<script setup lang="ts">
import MenuItem from "@/layout/components/Menu/menu-item.vue";
import { useRoutingMethod } from "@/hooks/useRoutingMethod";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
const route = useRoute();
const router = useRouter();
const themeStore = useThemeConfig();
const { collapsed, isAccordion, layoutType, asideDark } = storeToRefs(themeStore);
interface Props {
routeTree: Menu.MenuOptions[];
}
// props的数据类型
// type类型参考:https://cn.vuejs.org/guide/typescript/composition-api.html#typing-component-props
const props = withDefaults(defineProps<Props>(), {
routeTree: () => []
});
const onMenuItem = (path: string) => router.push(path);
const selectedMenu = computed(() => {
const { getAllParentRoute } = useRoutingMethod();
const find = getAllParentRoute(route.matched.at(-1).path);
if (!find) return "";
let path = "";
for (let i = find.length - 1; i >= 0; i--) {
if (find[i].meta && !find[i].meta.hide) {
path = find[i].path;
break;
}
}
return path;
});
</script>
<style lang="scss" scoped></style>
@@ -1,19 +1,19 @@
<template>
<s-svg-icon v-if="props.svgIcon" :name="props.svgIcon" :size="25" />
<component v-else-if="props.icon" :is="props.icon"></component>
</template>
<script setup lang="ts">
const props = defineProps({
svgIcon: {
type: String,
default: ""
},
icon: {
type: String,
default: ""
}
});
</script>
<style lang="scss" scoped></style>
<template>
<s-svg-icon v-if="props.svgIcon" :name="props.svgIcon" :size="25" />
<component v-else-if="props.icon" :is="props.icon"></component>
</template>
<script setup lang="ts">
const props = defineProps({
svgIcon: {
type: String,
default: ""
},
icon: {
type: String,
default: ""
}
});
</script>
<style lang="scss" scoped></style>
+37 -37
View File
@@ -1,37 +1,37 @@
<template>
<template v-for="item in props.routeTree" :key="item.path">
<a-sub-menu v-if="menuShow(item)" :key="item.path">
<template #icon v-if="item.meta.svgIcon || item.meta.icon">
<MenuItemIcon :svg-icon="item.meta.svgIcon" :icon="item.meta.icon" />
</template>
<template #title>{{ $t(`menu.${item.meta.title}`) }}</template>
<MenuItem :route-tree="item.children" />
</a-sub-menu>
<a-menu-item v-else-if="aMenuShow(item)" :key="item?.path">
<template #icon v-if="item.meta.svgIcon || item.meta.icon">
<MenuItemIcon :svg-icon="item.meta.svgIcon" :icon="item.meta.icon" />
</template>
<span>{{ $t(`menu.${item.meta.title}`) }}</span>
</a-menu-item>
</template>
</template>
<script setup lang="ts">
import MenuItem from "@/layout/components/Menu/menu-item.vue";
import MenuItemIcon from "@/layout/components/Menu/menu-item-icon.vue";
import { useMenuMethod } from "@/hooks/useMenuMethod";
defineOptions({ name: "MenuItem", inheritAttrs: false });
interface Props {
routeTree: Menu.MenuOptions[];
}
// props的数据类型
// type类型参考:https://cn.vuejs.org/guide/typescript/composition-api.html#typing-component-props
const props = withDefaults(defineProps<Props>(), {
routeTree: () => []
});
const { menuShow, aMenuShow } = useMenuMethod();
</script>
<style lang="scss" scoped></style>
<template>
<template v-for="item in props.routeTree" :key="item.path">
<a-sub-menu v-if="menuShow(item)" :key="item.path">
<template #icon v-if="item.meta.svgIcon || item.meta.icon">
<MenuItemIcon :svg-icon="item.meta.svgIcon" :icon="item.meta.icon" />
</template>
<template #title>{{ $t(`menu.${item.meta.title}`) }}</template>
<MenuItem :route-tree="item.children" />
</a-sub-menu>
<a-menu-item v-else-if="aMenuShow(item)" :key="item?.path">
<template #icon v-if="item.meta.svgIcon || item.meta.icon">
<MenuItemIcon :svg-icon="item.meta.svgIcon" :icon="item.meta.icon" />
</template>
<span>{{ $t(`menu.${item.meta.title}`) }}</span>
</a-menu-item>
</template>
</template>
<script setup lang="ts">
import MenuItem from "@/layout/components/Menu/menu-item.vue";
import MenuItemIcon from "@/layout/components/Menu/menu-item-icon.vue";
import { useMenuMethod } from "@/hooks/useMenuMethod";
defineOptions({ name: "MenuItem", inheritAttrs: false });
interface Props {
routeTree: Menu.MenuOptions[];
}
// props的数据类型
// type类型参考:https://cn.vuejs.org/guide/typescript/composition-api.html#typing-component-props
const props = withDefaults(defineProps<Props>(), {
routeTree: () => []
});
const { menuShow, aMenuShow } = useMenuMethod();
</script>
<style lang="scss" scoped></style>
+187 -187
View File
@@ -1,187 +1,187 @@
<template>
<div class="tabs">
<a-tabs
:editable="true"
:hide-content="true"
:active-key="currentRoute.path"
size="medium"
type="line"
@tab-click="onTabs"
@delete="onDelete"
>
<a-tab-pane v-for="item of tabsList" :key="item.path" :title="$t(`menu.${item.meta.title}`)" :closable="!item.meta.affix" />
</a-tabs>
<div class="tabs_setting">
<a-space>
<a-tooltip :content="$t(`system.refresh`)" position="bottom" mini>
<span ref="refreshRef" id="system-tabs-refresh" :class="rotateOpen && 'refresh'">
<icon-refresh :size="18" @click="refresh" />
</span>
</a-tooltip>
<a-dropdown trigger="hover" :popup-max-height="false">
<div class="setting" id="system-tabs-setting"><icon-apps :size="18" /></div>
<template #content>
<a-doption @click="closeCurrent">
<template #icon><icon-close /></template>
<template #default>{{ $t(`system.close-current`) }}</template>
</a-doption>
<a-doption @click="closeSides('left')">
<template #icon><icon-left /></template>
<template #default>{{ $t(`system.close-left-side`) }}</template>
</a-doption>
<a-doption @click="closeSides('right')">
<template #icon><icon-right /></template>
<template #default>{{ $t(`system.close-right-side`) }}</template>
</a-doption>
<a-doption @click="closeOther('other')">
<template #icon><icon-close-circle /></template>
<template #default>{{ $t(`system.close-other`) }}</template>
</a-doption>
<a-doption @click="closeOther('all')">
<template #icon><icon-folder-delete /></template>
<template #default>{{ $t(`system.close-all`) }}</template>
</a-doption>
</template>
</a-dropdown>
</a-space>
</div>
</div>
</template>
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { useRouteConfigStore } from "@/store/modules/route-config";
import { useThemeConfig } from "@/store/modules/theme-config";
const router = useRouter();
const routerStore = useRouteConfigStore();
const { tabsList, currentRoute } = storeToRefs(routerStore);
// 点击标签页,如果标签页存在,则跳转
const onTabs = (key: string) => {
router.push(key);
};
// 删除当前标签页并跳转到最后一个标签页
const onDelete = (path: string) => {
routerStore.removeTabsList(path);
routerStore.removeRouteName(path);
if (tabsList.value.length == 0) return;
if (currentRoute.value.path != path) return;
router.push(tabsList.value.at(-1).path);
};
// 刷新当前页
const rotateOpen = ref(false);
const refresh = () => {
rotateOpen.value = true;
setTimeout(() => {
rotateOpen.value = false;
}, 500);
const themeStore = useThemeConfig();
themeStore.setRefreshPage(false);
currentRoute.value.meta.keepAlive && routerStore.removeRouteName(currentRoute.value.path);
nextTick(() => {
themeStore.setRefreshPage(true);
currentRoute.value.meta.keepAlive && routerStore.setRoutePaths(currentRoute.value.path);
});
};
// 关闭当前
const closeCurrent = () => {
onDelete(currentRoute.value.path);
};
// 关闭右侧&关闭左侧
const closeSides = (type: string) => {
// 获得当前index
let currentIndex = tabsList.value.findIndex((item: Menu.MenuOptions) => item.path === currentRoute.value.path);
// 过滤出两侧可关闭的 affix: false 表示可关闭
let rightList = tabsList.value.filter((item: Menu.MenuOptions, index: number) => {
if (type == "right") {
if (index > currentIndex && !item.meta.affix) return item;
} else {
if (index < currentIndex && !item.meta.affix) return item;
}
});
// 返回可关闭名称
let rightPaths = rightList.map((item: Menu.MenuOptions) => item.path);
// 删除右侧
tabsList.value = tabsList.value.filter((item: Menu.MenuOptions) => !rightPaths.includes(item.path));
// 删除缓存
routerStore.removeRoutePaths(rightPaths);
};
// 关闭其它&关闭全部
const closeOther = (type: string) => {
// 过滤出可关闭项 affix: false 表示可关闭
let list = tabsList.value.filter((item: Menu.MenuOptions) => {
if (type == "other") {
if (item.path != currentRoute.value.path && !item.meta.affix) {
return item;
}
} else {
if (!item.meta.affix) {
return item;
}
}
});
// 返回可关闭名称
let rightNames = list.map((item: Menu.MenuOptions) => item.path);
// 删除可关闭项
tabsList.value = tabsList.value.filter((item: Menu.MenuOptions) => !rightNames.includes(item.path));
// 删除缓存
routerStore.removeRoutePaths(rightNames);
// 关闭全部,若当前被关闭则跳转最后一个
if (tabsList.value.length != 0 && !currentRoute.value.meta.affix && type == "all") {
router.push(tabsList.value.at(-1).path);
}
};
</script>
<style lang="scss" scoped>
.tabs {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-between;
height: 40px;
border-bottom: $border-1 solid $color-border-2;
.tabs_setting {
margin: 0 0 0 $margin;
.setting {
margin-right: $margin;
color: $color-text-2;
}
.refresh {
transform: rotate(360deg);
transition: transform 0.5s;
}
}
}
:deep(.arco-tabs-nav-tab) {
// 移入展示关闭icon
.arco-tabs-tab-closable {
svg {
width: 0;
transition: all 0.2s;
}
&:hover {
svg {
width: 1em;
}
}
}
// 消除tab移入的背景色
&:hover .arco-tabs-tab-title::before {
background: unset;
}
}
// 消除tabs底部边线
:deep(.arco-tabs-nav) {
&::before {
background: unset;
}
}
</style>
<template>
<div class="tabs">
<a-tabs
:editable="true"
:hide-content="true"
:active-key="currentRoute.path"
size="medium"
type="line"
@tab-click="onTabs"
@delete="onDelete"
>
<a-tab-pane v-for="item of tabsList" :key="item.path" :title="$t(`menu.${item.meta.title}`)" :closable="!item.meta.affix" />
</a-tabs>
<div class="tabs_setting">
<a-space>
<a-tooltip :content="$t(`system.refresh`)" position="bottom" mini>
<span ref="refreshRef" id="system-tabs-refresh" :class="rotateOpen && 'refresh'">
<icon-refresh :size="18" @click="refresh" />
</span>
</a-tooltip>
<a-dropdown trigger="hover" :popup-max-height="false">
<div class="setting" id="system-tabs-setting"><icon-apps :size="18" /></div>
<template #content>
<a-doption @click="closeCurrent">
<template #icon><icon-close /></template>
<template #default>{{ $t(`system.close-current`) }}</template>
</a-doption>
<a-doption @click="closeSides('left')">
<template #icon><icon-left /></template>
<template #default>{{ $t(`system.close-left-side`) }}</template>
</a-doption>
<a-doption @click="closeSides('right')">
<template #icon><icon-right /></template>
<template #default>{{ $t(`system.close-right-side`) }}</template>
</a-doption>
<a-doption @click="closeOther('other')">
<template #icon><icon-close-circle /></template>
<template #default>{{ $t(`system.close-other`) }}</template>
</a-doption>
<a-doption @click="closeOther('all')">
<template #icon><icon-folder-delete /></template>
<template #default>{{ $t(`system.close-all`) }}</template>
</a-doption>
</template>
</a-dropdown>
</a-space>
</div>
</div>
</template>
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { useRouteConfigStore } from "@/store/modules/route-config";
import { useThemeConfig } from "@/store/modules/theme-config";
const router = useRouter();
const routerStore = useRouteConfigStore();
const { tabsList, currentRoute } = storeToRefs(routerStore);
// 点击标签页,如果标签页存在,则跳转
const onTabs = (key: string) => {
router.push(key);
};
// 删除当前标签页并跳转到最后一个标签页
const onDelete = (path: string) => {
routerStore.removeTabsList(path);
routerStore.removeRouteName(path);
if (tabsList.value.length == 0) return;
if (currentRoute.value.path != path) return;
router.push(tabsList.value.at(-1).path);
};
// 刷新当前页
const rotateOpen = ref(false);
const refresh = () => {
rotateOpen.value = true;
setTimeout(() => {
rotateOpen.value = false;
}, 500);
const themeStore = useThemeConfig();
themeStore.setRefreshPage(false);
currentRoute.value.meta.keepAlive && routerStore.removeRouteName(currentRoute.value.path);
nextTick(() => {
themeStore.setRefreshPage(true);
currentRoute.value.meta.keepAlive && routerStore.setRoutePaths(currentRoute.value.path);
});
};
// 关闭当前
const closeCurrent = () => {
onDelete(currentRoute.value.path);
};
// 关闭右侧&关闭左侧
const closeSides = (type: string) => {
// 获得当前index
let currentIndex = tabsList.value.findIndex((item: Menu.MenuOptions) => item.path === currentRoute.value.path);
// 过滤出两侧可关闭的 affix: false 表示可关闭
let rightList = tabsList.value.filter((item: Menu.MenuOptions, index: number) => {
if (type == "right") {
if (index > currentIndex && !item.meta.affix) return item;
} else {
if (index < currentIndex && !item.meta.affix) return item;
}
});
// 返回可关闭名称
let rightPaths = rightList.map((item: Menu.MenuOptions) => item.path);
// 删除右侧
tabsList.value = tabsList.value.filter((item: Menu.MenuOptions) => !rightPaths.includes(item.path));
// 删除缓存
routerStore.removeRoutePaths(rightPaths);
};
// 关闭其它&关闭全部
const closeOther = (type: string) => {
// 过滤出可关闭项 affix: false 表示可关闭
let list = tabsList.value.filter((item: Menu.MenuOptions) => {
if (type == "other") {
if (item.path != currentRoute.value.path && !item.meta.affix) {
return item;
}
} else {
if (!item.meta.affix) {
return item;
}
}
});
// 返回可关闭名称
let rightNames = list.map((item: Menu.MenuOptions) => item.path);
// 删除可关闭项
tabsList.value = tabsList.value.filter((item: Menu.MenuOptions) => !rightNames.includes(item.path));
// 删除缓存
routerStore.removeRoutePaths(rightNames);
// 关闭全部,若当前被关闭则跳转最后一个
if (tabsList.value.length != 0 && !currentRoute.value.meta.affix && type == "all") {
router.push(tabsList.value.at(-1).path);
}
};
</script>
<style lang="scss" scoped>
.tabs {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-between;
height: 40px;
border-bottom: $border-1 solid $color-border-2;
.tabs_setting {
margin: 0 0 0 $margin;
.setting {
margin-right: $margin;
color: $color-text-2;
}
.refresh {
transform: rotate(360deg);
transition: transform 0.5s;
}
}
}
:deep(.arco-tabs-nav-tab) {
// 移入展示关闭icon
.arco-tabs-tab-closable {
svg {
width: 0;
transition: all 0.2s;
}
&:hover {
svg {
width: 1em;
}
}
}
// 消除tab移入的背景色
&:hover .arco-tabs-tab-title::before {
background: unset;
}
}
// 消除tabs底部边线
:deep(.arco-tabs-nav) {
&::before {
background: unset;
}
}
</style>
@@ -1,98 +1,98 @@
<template>
<a-drawer
:width="220"
class="drawer-aside"
placement="left"
:header="false"
:footer="false"
:visible="!collapsed"
@cancel="handleCancel"
unmount-on-close
>
<div :class="asideDark ? 'aside dark' : 'aside'">
<Logo />
<a-layout-sider class="layout_side" :width="220">
<a-scrollbar style="height: 100%; overflow: auto" outer-class="scrollbar"><Menu :route-tree="routeTree" /></a-scrollbar>
</a-layout-sider>
</div>
</a-drawer>
</template>
<script setup lang="ts">
import Logo from "@/layout/components/Logo/index.vue";
import Menu from "@/layout/components/Menu/index.vue";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useRouteConfigStore } from "@/store/modules/route-config";
const themeStore = useThemeConfig();
const { collapsed, asideDark } = storeToRefs(themeStore);
const routerStore = useRouteConfigStore();
const { routeTree } = storeToRefs(routerStore);
const handleCancel = () => {
collapsed.value = true;
};
</script>
<style lang="scss" scoped>
.aside {
display: flex;
flex-direction: column;
height: 100vh;
}
.dark {
background: #232324;
}
.layout_side {
flex: 1;
overflow: hidden;
.scrollbar {
height: 100%;
}
}
// 修改左侧滚动条宽度
:deep(.arco-scrollbar-thumb-direction-vertical .arco-scrollbar-thumb-bar) {
width: 4px;
margin-left: 8px;
}
// 去掉右侧阴影并替换为边线
:deep(.arco-layout-sider-light) {
border-right: $border-1 solid $color-border-2;
box-shadow: unset;
}
// 解决折叠菜单的icon不居中问题
:deep(.arco-menu-vertical.arco-menu-collapsed) {
// 消除icon的自带padding值,并且让元素居中
.arco-menu-has-icon {
justify-content: center;
padding: 0;
}
// 消除icon的自带margin-right值,并且设置icon的padding值以保留icon空隙
.arco-menu-icon {
padding: 10px 0;
margin-right: 0;
}
// 消除title占位
.arco-menu-title {
display: none;
}
}
// 去掉sider背景
.arco-layout-sider {
background: unset;
}
</style>
<style lang="scss">
.drawer-aside {
.arco-drawer .arco-drawer-body {
padding: 0;
overflow: hidden;
}
}
</style>
<template>
<a-drawer
:width="220"
class="drawer-aside"
placement="left"
:header="false"
:footer="false"
:visible="!collapsed"
@cancel="handleCancel"
unmount-on-close
>
<div :class="asideDark ? 'aside dark' : 'aside'">
<Logo />
<a-layout-sider class="layout_side" :width="220">
<a-scrollbar style="height: 100%; overflow: auto" outer-class="scrollbar"><Menu :route-tree="routeTree" /></a-scrollbar>
</a-layout-sider>
</div>
</a-drawer>
</template>
<script setup lang="ts">
import Logo from "@/layout/components/Logo/index.vue";
import Menu from "@/layout/components/Menu/index.vue";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useRouteConfigStore } from "@/store/modules/route-config";
const themeStore = useThemeConfig();
const { collapsed, asideDark } = storeToRefs(themeStore);
const routerStore = useRouteConfigStore();
const { routeTree } = storeToRefs(routerStore);
const handleCancel = () => {
collapsed.value = true;
};
</script>
<style lang="scss" scoped>
.aside {
display: flex;
flex-direction: column;
height: 100vh;
}
.dark {
background: #232324;
}
.layout_side {
flex: 1;
overflow: hidden;
.scrollbar {
height: 100%;
}
}
// 修改左侧滚动条宽度
:deep(.arco-scrollbar-thumb-direction-vertical .arco-scrollbar-thumb-bar) {
width: 4px;
margin-left: 8px;
}
// 去掉右侧阴影并替换为边线
:deep(.arco-layout-sider-light) {
border-right: $border-1 solid $color-border-2;
box-shadow: unset;
}
// 解决折叠菜单的icon不居中问题
:deep(.arco-menu-vertical.arco-menu-collapsed) {
// 消除icon的自带padding值,并且让元素居中
.arco-menu-has-icon {
justify-content: center;
padding: 0;
}
// 消除icon的自带margin-right值,并且设置icon的padding值以保留icon空隙
.arco-menu-icon {
padding: 10px 0;
margin-right: 0;
}
// 消除title占位
.arco-menu-title {
display: none;
}
}
// 去掉sider背景
.arco-layout-sider {
background: unset;
}
</style>
<style lang="scss">
.drawer-aside {
.arco-drawer .arco-drawer-body {
padding: 0;
overflow: hidden;
}
}
</style>
+24 -24
View File
@@ -1,24 +1,24 @@
<template>
<div>
<s-lang-provider>
<component :is="layouts[layoutType]" />
</s-lang-provider>
</div>
</template>
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
const themeStore = useThemeConfig();
const { layoutType } = storeToRefs(themeStore);
// 引入组件-异步组件
const layouts: any = {
layoutDefaults: defineAsyncComponent(() => import("@/layout/layout-defaults/index.vue")),
layoutHead: defineAsyncComponent(() => import("@/layout/layout-head/index.vue")),
layoutMixing: defineAsyncComponent(() => import("@/layout/layout-mixing/index.vue"))
};
</script>
<style lang="scss" scoped></style>
<template>
<div>
<s-lang-provider>
<component :is="layouts[layoutType]" />
</s-lang-provider>
</div>
</template>
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
const themeStore = useThemeConfig();
const { layoutType } = storeToRefs(themeStore);
// 引入组件-异步组件
const layouts: any = {
layoutDefaults: defineAsyncComponent(() => import("@/layout/layout-defaults/index.vue")),
layoutHead: defineAsyncComponent(() => import("@/layout/layout-head/index.vue")),
layoutMixing: defineAsyncComponent(() => import("@/layout/layout-mixing/index.vue"))
};
</script>
<style lang="scss" scoped></style>
+37 -37
View File
@@ -1,37 +1,37 @@
<template>
<a-layout class="layout" :has-sider="true">
<Aside v-if="isPc" />
<a-layout class="layout-right">
<Header />
<Main />
<Footer v-if="isFooter" />
</a-layout>
</a-layout>
</template>
<script setup lang="ts">
import Aside from "@/layout/components/Aside/index.vue";
import Header from "@/layout/components/Header/index.vue";
import Main from "@/layout/components/Main/index.vue";
import Footer from "@/layout/components/Footer/index.vue";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useDevicesSize } from "@/hooks/useDevicesSize";
defineOptions({ name: "LayoutDefaults" });
const themeStore = useThemeConfig();
let { isFooter } = storeToRefs(themeStore);
const { isPc } = useDevicesSize();
</script>
<style lang="scss" scoped>
.layout {
height: 100vh;
}
.layout-right {
display: grid;
grid-template-rows: auto 1fr auto;
}
</style>
<template>
<a-layout class="layout" :has-sider="true">
<Aside v-if="isPc" />
<a-layout class="layout-right">
<Header />
<Main />
<Footer v-if="isFooter" />
</a-layout>
</a-layout>
</template>
<script setup lang="ts">
import Aside from "@/layout/components/Aside/index.vue";
import Header from "@/layout/components/Header/index.vue";
import Main from "@/layout/components/Main/index.vue";
import Footer from "@/layout/components/Footer/index.vue";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useDevicesSize } from "@/hooks/useDevicesSize";
defineOptions({ name: "LayoutDefaults" });
const themeStore = useThemeConfig();
let { isFooter } = storeToRefs(themeStore);
const { isPc } = useDevicesSize();
</script>
<style lang="scss" scoped>
.layout {
height: 100vh;
}
.layout-right {
display: grid;
grid-template-rows: auto 1fr auto;
}
</style>
+134 -134
View File
@@ -1,134 +1,134 @@
<template>
<div class="layout-head">
<div class="layout-head-top">
<a-layout-header class="header">
<div class="header-logo" v-if="!isMobile">
<Logo />
</div>
<div class="layout-head-menu" v-if="!isMobile">
<a-menu
v-if="drawing"
mode="horizontal"
:selected-keys="[selectedMenu]"
@menu-item-click="onMenuItem"
:popup-max-height="600"
>
<template v-for="item in routeTree" :key="item.path">
<a-sub-menu v-if="menuShow(item)" :key="item.path" :popup-max-height="600">
<template #icon v-if="item.meta.svgIcon || item.meta.icon">
<MenuItemIcon :svg-icon="item.meta.svgIcon" :icon="item.meta.icon" />
</template>
<template #title>{{ $t(`menu.${item.meta.title}`) }}</template>
<MenuItem :route-tree="item.children" />
</a-sub-menu>
<a-menu-item v-else-if="aMenuShow(item)" :key="item?.path">
<template #icon v-if="item.meta.svgIcon || item.meta.icon">
<MenuItemIcon :svg-icon="item.meta.svgIcon" :icon="item.meta.icon" />
</template>
<span>{{ $t(`menu.${item.meta.title}`) }}</span>
</a-menu-item>
</template>
</a-menu>
</div>
<ButtonCollapsed v-else />
<HeaderRight />
</a-layout-header>
<Main />
<Footer v-if="isFooter" />
</div>
</div>
</template>
<script setup lang="ts">
import Logo from "@/layout/components/Logo/index.vue";
import HeaderRight from "@/layout/components/Header/components/header-right/index.vue";
import Main from "@/layout/components/Main/index.vue";
import Footer from "@/layout/components/Footer/index.vue";
import MenuItem from "@/layout/components/Menu/menu-item.vue";
import MenuItemIcon from "@/layout/components/Menu/menu-item-icon.vue";
import ButtonCollapsed from "@/layout/components/Header/components/button-collapsed/index.vue";
import { useRoutingMethod } from "@/hooks/useRoutingMethod";
import { storeToRefs } from "pinia";
import { useRouteConfigStore } from "@/store/modules/route-config";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useMenuMethod } from "@/hooks/useMenuMethod";
import { useDevicesSize } from "@/hooks/useDevicesSize";
defineOptions({ name: "LayoutHead" });
const route = useRoute();
const router = useRouter();
const routerStore = useRouteConfigStore();
const themeStore = useThemeConfig();
const { routeTree } = storeToRefs(routerStore);
const { isFooter, language } = storeToRefs(themeStore);
const { isMobile } = useDevicesSize();
const { menuShow, aMenuShow } = useMenuMethod();
const drawing = ref<boolean>(true);
watch(language, () => {
drawing.value = false;
nextTick(() => (drawing.value = true));
});
const onMenuItem = (path: string) => router.push(path);
const selectedMenu = computed(() => {
const { getAllParentRoute } = useRoutingMethod();
const find = getAllParentRoute(route.matched.at(-1).path);
if (!find) return "";
let path = "";
for (let i = find.length - 1; i >= 0; i--) {
if (find[i].meta && !find[i].meta.hide) {
path = find[i].path;
break;
}
}
return path;
});
</script>
<style lang="scss" scoped>
.layout-head {
height: 100vh;
&-top {
position: relative;
display: grid;
grid-template-rows: auto 1fr auto;
height: 100%;
}
}
.header {
position: relative;
box-sizing: border-box;
display: flex;
align-items: center;
width: 100%;
height: 60px;
padding: 0 $padding;
overflow: hidden;
border-bottom: $border-1 solid $color-border-2;
.header-logo {
max-width: 180px;
}
.layout-head-menu {
display: flex;
flex: 1;
overflow: hidden;
}
}
:deep(.arco-menu-pop) {
white-space: nowrap;
}
// 横向菜单样式修改
:deep(.arco-menu-horizontal) {
flex: 1;
overflow: hidden;
.arco-menu-inner {
padding-left: 0; // 横向排列,禁用左padding
.arco-menu-overflow-wrap {
white-space: nowrap; // 禁用换行,否则会导致菜单换行闪烁
}
}
}
</style>
<template>
<div class="layout-head">
<div class="layout-head-top">
<a-layout-header class="header">
<div class="header-logo" v-if="!isMobile">
<Logo />
</div>
<div class="layout-head-menu" v-if="!isMobile">
<a-menu
v-if="drawing"
mode="horizontal"
:selected-keys="[selectedMenu]"
@menu-item-click="onMenuItem"
:popup-max-height="600"
>
<template v-for="item in routeTree" :key="item.path">
<a-sub-menu v-if="menuShow(item)" :key="item.path" :popup-max-height="600">
<template #icon v-if="item.meta.svgIcon || item.meta.icon">
<MenuItemIcon :svg-icon="item.meta.svgIcon" :icon="item.meta.icon" />
</template>
<template #title>{{ $t(`menu.${item.meta.title}`) }}</template>
<MenuItem :route-tree="item.children" />
</a-sub-menu>
<a-menu-item v-else-if="aMenuShow(item)" :key="item?.path">
<template #icon v-if="item.meta.svgIcon || item.meta.icon">
<MenuItemIcon :svg-icon="item.meta.svgIcon" :icon="item.meta.icon" />
</template>
<span>{{ $t(`menu.${item.meta.title}`) }}</span>
</a-menu-item>
</template>
</a-menu>
</div>
<ButtonCollapsed v-else />
<HeaderRight />
</a-layout-header>
<Main />
<Footer v-if="isFooter" />
</div>
</div>
</template>
<script setup lang="ts">
import Logo from "@/layout/components/Logo/index.vue";
import HeaderRight from "@/layout/components/Header/components/header-right/index.vue";
import Main from "@/layout/components/Main/index.vue";
import Footer from "@/layout/components/Footer/index.vue";
import MenuItem from "@/layout/components/Menu/menu-item.vue";
import MenuItemIcon from "@/layout/components/Menu/menu-item-icon.vue";
import ButtonCollapsed from "@/layout/components/Header/components/button-collapsed/index.vue";
import { useRoutingMethod } from "@/hooks/useRoutingMethod";
import { storeToRefs } from "pinia";
import { useRouteConfigStore } from "@/store/modules/route-config";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useMenuMethod } from "@/hooks/useMenuMethod";
import { useDevicesSize } from "@/hooks/useDevicesSize";
defineOptions({ name: "LayoutHead" });
const route = useRoute();
const router = useRouter();
const routerStore = useRouteConfigStore();
const themeStore = useThemeConfig();
const { routeTree } = storeToRefs(routerStore);
const { isFooter, language } = storeToRefs(themeStore);
const { isMobile } = useDevicesSize();
const { menuShow, aMenuShow } = useMenuMethod();
const drawing = ref<boolean>(true);
watch(language, () => {
drawing.value = false;
nextTick(() => (drawing.value = true));
});
const onMenuItem = (path: string) => router.push(path);
const selectedMenu = computed(() => {
const { getAllParentRoute } = useRoutingMethod();
const find = getAllParentRoute(route.matched.at(-1).path);
if (!find) return "";
let path = "";
for (let i = find.length - 1; i >= 0; i--) {
if (find[i].meta && !find[i].meta.hide) {
path = find[i].path;
break;
}
}
return path;
});
</script>
<style lang="scss" scoped>
.layout-head {
height: 100vh;
&-top {
position: relative;
display: grid;
grid-template-rows: auto 1fr auto;
height: 100%;
}
}
.header {
position: relative;
box-sizing: border-box;
display: flex;
align-items: center;
width: 100%;
height: 60px;
padding: 0 $padding;
overflow: hidden;
border-bottom: $border-1 solid $color-border-2;
.header-logo {
max-width: 180px;
}
.layout-head-menu {
display: flex;
flex: 1;
overflow: hidden;
}
}
:deep(.arco-menu-pop) {
white-space: nowrap;
}
// 横向菜单样式修改
:deep(.arco-menu-horizontal) {
flex: 1;
overflow: hidden;
.arco-menu-inner {
padding-left: 0; // 横向排列,禁用左padding
.arco-menu-overflow-wrap {
white-space: nowrap; // 禁用换行,否则会导致菜单换行闪烁
}
}
}
</style>
+217 -217
View File
@@ -1,217 +1,217 @@
<template>
<a-layout class="layout">
<div :class="asideDark ? 'aside dark' : 'aside'" v-if="isPc">
<Logo />
<a-layout-sider :collapsed="collapsed" breakpoint="xl" class="layout_side" :width="220">
<a-scrollbar style="height: 100%; overflow: auto" outer-class="scrollbar"><Menu :route-tree="routeList" /></a-scrollbar>
</a-layout-sider>
</div>
<a-layout class="layout-right">
<a-layout-header class="header">
<div class="header-left">
<ButtonCollapsed />
<Breadcrumb v-if="!isPc" />
</div>
<div class="layout-head-menu" v-if="isPc">
<a-menu
v-if="drawing"
mode="horizontal"
:selected-keys="[selectedMenu]"
@menu-item-click="onMenuItem"
:popup-max-height="600"
>
<template v-for="item in routeTree" :key="item.path">
<a-menu-item v-if="!item.meta.hide" :key="item.path" :popup-max-height="600">
<template #icon v-if="item.meta.svgIcon || item.meta.icon">
<MenuItemIcon :svg-icon="item.meta.svgIcon" :icon="item.meta.icon" />
</template>
<span>{{ $t(`menu.${item.meta.title}`) }}</span>
</a-menu-item>
</template>
</a-menu>
</div>
<HeaderRight />
</a-layout-header>
<Main />
<Footer v-if="isFooter" />
</a-layout>
</a-layout>
</template>
<script setup lang="ts">
import Logo from "@/layout/components/Logo/index.vue";
import Main from "@/layout/components/Main/index.vue";
import Footer from "@/layout/components/Footer/index.vue";
import Menu from "@/layout/components/Menu/index.vue";
import HeaderRight from "@/layout/components/Header/components/header-right/index.vue";
import MenuItemIcon from "@/layout/components/Menu/menu-item-icon.vue";
import ButtonCollapsed from "@/layout/components/Header/components/button-collapsed/index.vue";
import Breadcrumb from "@/layout/components/Header/components/Breadcrumb/index.vue";
import { useRouteConfigStore } from "@/store/modules/route-config";
import { useRoutingMethod } from "@/hooks/useRoutingMethod";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useDevicesSize } from "@/hooks/useDevicesSize";
defineOptions({ name: "LayoutMixing" });
const route = useRoute();
const router = useRouter();
const routerStore = useRouteConfigStore();
const themeStore = useThemeConfig();
const { isFooter, collapsed, asideDark, language } = storeToRefs(themeStore);
const { routeTree } = storeToRefs(routerStore);
const { isPc } = useDevicesSize();
const drawing = ref<boolean>(true);
watch(language, () => {
drawing.value = false;
nextTick(() => (drawing.value = true));
});
// 横向菜单点击事件
// 将一级菜单下的children给左侧菜单
// 如果没有children则直接自身菜单给左侧菜单
const routeList = ref<any>([]);
const onMenuItem = (path: string) => {
const { findLinearArray } = useRoutingMethod();
const find = findLinearArray(path);
// 路由存在则存入并跳转,不存在则跳404
if (find) {
// 给左侧树赋值
setAside(find);
// 若有重定向,则跳转到重定向的路由
// 如果有子路由则重定向到自己的第一个菜单
// 如果没有子路由则说明当前父级是一个菜单,直接跳转
let path = "";
if (find.redirect) {
path = find.redirect;
} else if (find.children && find.children.length > 0) {
path = find.children[0].path;
} else {
path = find.path;
}
router.push(path);
} else {
router.push("/404");
}
};
// 给左侧树赋值
const setAsideMenu = (find: Menu.MenuOptions) => {
// 将父级的chindren给左侧树
if (find.children && find.children.length > 0) {
routeList.value = find.children;
} else {
// 如果没有则直接将父级给左侧树,做一级兜底
routeList.value = [find];
}
};
const setAside = debounce(setAsideMenu, 150);
// 由于刷新后,路由信息丢失,所以需要重新获取
// 混合布局的横向菜单为顶层路由下的一级菜单
const selectedMenu = computed(() => {
const { getAllParentRoute } = useRoutingMethod();
// 动态路由参数会在path拼接,导致匹配失败
// 这取matched做路由匹配
const find = getAllParentRoute(route.matched.at(-1).path);
if (find) {
setAside(find[0]);
return find[0].path;
}
return "";
});
</script>
<style lang="scss" scoped>
.layout {
height: 100vh;
}
.dark {
background: #232324;
}
.layout_side {
height: calc(100% - 60px);
.scrollbar {
height: 100%;
}
}
// 修改左侧滚动条宽度
:deep(.arco-scrollbar-thumb-direction-vertical .arco-scrollbar-thumb-bar) {
width: 4px;
margin-left: 8px;
}
// 去掉右侧阴影并替换为边线
:deep(.arco-layout-sider-light) {
border-right: $border-1 solid $color-border-2;
box-shadow: unset;
}
// 解决折叠菜单的icon不居中问题
:deep(.arco-menu-vertical.arco-menu-collapsed) {
// 消除icon的自带padding值,并且让元素居中
.arco-menu-has-icon {
justify-content: center;
padding: 0;
}
// 消除icon的自带margin-right值,并且设置icon的padding值以保留icon空隙
.arco-menu-icon {
padding: 10px 0;
margin-right: 0;
}
// 消除title占位
.arco-menu-title {
display: none;
}
}
// 去掉sider背景
.arco-layout-sider {
background: unset;
}
.layout-right {
display: grid;
grid-template-rows: auto 1fr auto;
height: 100%;
.header {
position: relative;
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-between;
height: 60px;
padding: 0 $padding;
overflow: hidden;
border-bottom: $border-1 solid $color-border-2;
.header-left {
display: flex;
align-items: center;
}
}
.layout-head-menu {
display: flex;
flex: 1;
overflow: hidden;
}
}
:deep(.arco-menu-pop) {
white-space: nowrap;
}
// 横向菜单样式修改
:deep(.arco-menu-horizontal) {
flex: 1;
overflow: hidden;
.arco-menu-inner {
padding-left: 0; // 横向排列,禁用左padding
.arco-menu-overflow-wrap {
white-space: nowrap; // 禁用换行,否则会导致菜单换行闪烁
}
}
}
</style>
<template>
<a-layout class="layout">
<div :class="asideDark ? 'aside dark' : 'aside'" v-if="isPc">
<Logo />
<a-layout-sider :collapsed="collapsed" breakpoint="xl" class="layout_side" :width="220">
<a-scrollbar style="height: 100%; overflow: auto" outer-class="scrollbar"><Menu :route-tree="routeList" /></a-scrollbar>
</a-layout-sider>
</div>
<a-layout class="layout-right">
<a-layout-header class="header">
<div class="header-left">
<ButtonCollapsed />
<Breadcrumb v-if="!isPc" />
</div>
<div class="layout-head-menu" v-if="isPc">
<a-menu
v-if="drawing"
mode="horizontal"
:selected-keys="[selectedMenu]"
@menu-item-click="onMenuItem"
:popup-max-height="600"
>
<template v-for="item in routeTree" :key="item.path">
<a-menu-item v-if="!item.meta.hide" :key="item.path" :popup-max-height="600">
<template #icon v-if="item.meta.svgIcon || item.meta.icon">
<MenuItemIcon :svg-icon="item.meta.svgIcon" :icon="item.meta.icon" />
</template>
<span>{{ $t(`menu.${item.meta.title}`) }}</span>
</a-menu-item>
</template>
</a-menu>
</div>
<HeaderRight />
</a-layout-header>
<Main />
<Footer v-if="isFooter" />
</a-layout>
</a-layout>
</template>
<script setup lang="ts">
import Logo from "@/layout/components/Logo/index.vue";
import Main from "@/layout/components/Main/index.vue";
import Footer from "@/layout/components/Footer/index.vue";
import Menu from "@/layout/components/Menu/index.vue";
import HeaderRight from "@/layout/components/Header/components/header-right/index.vue";
import MenuItemIcon from "@/layout/components/Menu/menu-item-icon.vue";
import ButtonCollapsed from "@/layout/components/Header/components/button-collapsed/index.vue";
import Breadcrumb from "@/layout/components/Header/components/Breadcrumb/index.vue";
import { useRouteConfigStore } from "@/store/modules/route-config";
import { useRoutingMethod } from "@/hooks/useRoutingMethod";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
import { useDevicesSize } from "@/hooks/useDevicesSize";
defineOptions({ name: "LayoutMixing" });
const route = useRoute();
const router = useRouter();
const routerStore = useRouteConfigStore();
const themeStore = useThemeConfig();
const { isFooter, collapsed, asideDark, language } = storeToRefs(themeStore);
const { routeTree } = storeToRefs(routerStore);
const { isPc } = useDevicesSize();
const drawing = ref<boolean>(true);
watch(language, () => {
drawing.value = false;
nextTick(() => (drawing.value = true));
});
// 横向菜单点击事件
// 将一级菜单下的children给左侧菜单
// 如果没有children则直接自身菜单给左侧菜单
const routeList = ref<any>([]);
const onMenuItem = (path: string) => {
const { findLinearArray } = useRoutingMethod();
const find = findLinearArray(path);
// 路由存在则存入并跳转,不存在则跳404
if (find) {
// 给左侧树赋值
setAside(find);
// 若有重定向,则跳转到重定向的路由
// 如果有子路由则重定向到自己的第一个菜单
// 如果没有子路由则说明当前父级是一个菜单,直接跳转
let path = "";
if (find.redirect) {
path = find.redirect;
} else if (find.children && find.children.length > 0) {
path = find.children[0].path;
} else {
path = find.path;
}
router.push(path);
} else {
router.push("/404");
}
};
// 给左侧树赋值
const setAsideMenu = (find: Menu.MenuOptions) => {
// 将父级的chindren给左侧树
if (find.children && find.children.length > 0) {
routeList.value = find.children;
} else {
// 如果没有则直接将父级给左侧树,做一级兜底
routeList.value = [find];
}
};
const setAside = debounce(setAsideMenu, 150);
// 由于刷新后,路由信息丢失,所以需要重新获取
// 混合布局的横向菜单为顶层路由下的一级菜单
const selectedMenu = computed(() => {
const { getAllParentRoute } = useRoutingMethod();
// 动态路由参数会在path拼接,导致匹配失败
// 这取matched做路由匹配
const find = getAllParentRoute(route.matched.at(-1).path);
if (find) {
setAside(find[0]);
return find[0].path;
}
return "";
});
</script>
<style lang="scss" scoped>
.layout {
height: 100vh;
}
.dark {
background: #232324;
}
.layout_side {
height: calc(100% - 60px);
.scrollbar {
height: 100%;
}
}
// 修改左侧滚动条宽度
:deep(.arco-scrollbar-thumb-direction-vertical .arco-scrollbar-thumb-bar) {
width: 4px;
margin-left: 8px;
}
// 去掉右侧阴影并替换为边线
:deep(.arco-layout-sider-light) {
border-right: $border-1 solid $color-border-2;
box-shadow: unset;
}
// 解决折叠菜单的icon不居中问题
:deep(.arco-menu-vertical.arco-menu-collapsed) {
// 消除icon的自带padding值,并且让元素居中
.arco-menu-has-icon {
justify-content: center;
padding: 0;
}
// 消除icon的自带margin-right值,并且设置icon的padding值以保留icon空隙
.arco-menu-icon {
padding: 10px 0;
margin-right: 0;
}
// 消除title占位
.arco-menu-title {
display: none;
}
}
// 去掉sider背景
.arco-layout-sider {
background: unset;
}
.layout-right {
display: grid;
grid-template-rows: auto 1fr auto;
height: 100%;
.header {
position: relative;
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-between;
height: 60px;
padding: 0 $padding;
overflow: hidden;
border-bottom: $border-1 solid $color-border-2;
.header-left {
display: flex;
align-items: center;
}
}
.layout-head-menu {
display: flex;
flex: 1;
overflow: hidden;
}
}
:deep(.arco-menu-pop) {
white-space: nowrap;
}
// 横向菜单样式修改
:deep(.arco-menu-horizontal) {
flex: 1;
overflow: hidden;
.arco-menu-inner {
padding-left: 0; // 横向排列,禁用左padding
.arco-menu-overflow-wrap {
white-space: nowrap; // 禁用换行,否则会导致菜单换行闪烁
}
}
}
</style>
+43 -43
View File
@@ -1,43 +1,43 @@
import { createApp } from "vue";
import "@/style.css";
import App from "@/App.vue";
// arco-design
import ArcoVue from "@arco-design/web-vue";
// vue-router
import router from "@/router/index";
// pinia
import pinia from "@/store/index";
// arco-css
import "@arco-design/web-vue/dist/arco.css";
// vchart-arco-theme 主题关联-黑暗模式
import { initVChartArcoTheme } from "@visactor/vchart-arco-theme";
// 额外引入图标库
import ArcoVueIcon from "@arco-design/web-vue/es/icon";
// 注册全局svg
import "virtual:svg-icons-register";
// 引入i18n
import i18n from "@/lang/index";
// 引入字体
import "@/assets/fonts/fonts.scss";
// 引入自定义指令
import directives from "@/directives/index";
// vchart黑暗模式
// https://arco.design/react/docs/vchart
initVChartArcoTheme();
const app = createApp(App);
// app.use(plugin, options)
// 其中 plugin 表示要传递的插件对象, options 参数是可选的,表示选项配置
// https://cn.vuejs.org/api/application.html#app-use
app.use(ArcoVue, {
componentPrefix: "arco"
});
app.use(pinia);
app.use(ArcoVueIcon);
app.use(router);
app.use(i18n);
app.use(directives);
app.mount("#app");
import { createApp } from "vue";
import "@/style.css";
import App from "@/App.vue";
// arco-design
import ArcoVue from "@arco-design/web-vue";
// vue-router
import router from "@/router/index";
// pinia
import pinia from "@/store/index";
// arco-css
import "@arco-design/web-vue/dist/arco.css";
// vchart-arco-theme 主题关联-黑暗模式
import { initVChartArcoTheme } from "@visactor/vchart-arco-theme";
// 额外引入图标库
import ArcoVueIcon from "@arco-design/web-vue/es/icon";
// 注册全局svg
import "virtual:svg-icons-register";
// 引入i18n
import i18n from "@/lang/index";
// 引入字体
import "@/assets/fonts/fonts.scss";
// 引入自定义指令
import directives from "@/directives/index";
// vchart黑暗模式
// https://arco.design/react/docs/vchart
initVChartArcoTheme();
const app = createApp(App);
// app.use(plugin, options)
// 其中 plugin 表示要传递的插件对象, options 参数是可选的,表示选项配置
// https://cn.vuejs.org/api/application.html#app-use
app.use(ArcoVue, {
componentPrefix: "arco"
});
app.use(pinia);
app.use(ArcoVueIcon);
app.use(router);
app.use(i18n);
app.use(directives);
app.mount("#app");
File diff suppressed because it is too large Load Diff
+187 -187
View File
@@ -1,187 +1,187 @@
import Mock from "mockjs";
/** 返回成功数据 */
export const resultSuccess = (data: unknown) => {
return Mock.mock({
code: 200,
data,
message: "请求成功",
success: true
});
};
/** 返回失败数据 */
export const resultError = (data: unknown, message: string, code = 500) => {
return Mock.mock({
code,
data,
message,
success: false
});
};
/**
* 路由树递归排序
* 1、先给当前层排序
* 2、若当前层有children则递归排序
* @param {array} tree 根据角色权限过滤后的路由树
* @returns 返回排序之后的树
*/
export const treeSort = (tree: Menu.MenuOptions[]) => {
if (!tree || tree.length == 0) return [];
tree.sort((a: Menu.MenuOptions, b: Menu.MenuOptions) => {
// a和b都是undefined则相等
if (a.meta.sort != 0 && !a.meta.sort && b.meta.sort != 0 && !b.meta.sort) {
return 0;
}
// a是undefined则a被排在b之后
if (a.meta.sort != 0 && !a.meta.sort) return 1;
// b是undefined则b被排在a之后
if (b.meta.sort != 0 && !b.meta.sort) return -1;
return a.meta.sort - b.meta.sort;
});
// 深层递归
return tree.map((item: any) => {
if (item?.children?.length > 0) {
item.children = treeSort(item.children);
}
return item;
});
};
/**
* 过滤路由树,返回有权限的树
* 1、根据角色权限过滤原始路由树
* 2、过滤禁用的菜单,该菜单是不可访问的,直接去掉
* @param {array} tree 根据角色权限过滤原始路由树
* @returns 返回有权限的树
*/
export const filterByDisable = (tree: any, userRoles: Array<string>) => {
return tree.filter((item: any) => {
// 过滤角色权限
if (item?.meta?.roles) {
if (!roleBase(item.meta.roles, userRoles)) return false;
}
// 过滤是否禁用
if (item?.meta?.disable) return false;
return true;
});
};
/**
* 校验该角色是否有路由权限
* @param {array} roles 路由的角色权限
* @returns 是否有权限 true是 false否
*/
export const roleBase = (roles: Array<string>, userRoles: Array<string>) => {
// 如果是admin则直接放行
if (userRoles.includes("admin")) return true;
// 否则判断权限
return userRoles.some((item: string) => roles.includes(item));
};
/**
* 深拷贝
* @param { string } data 需要深拷贝的数据
* @returns 深拷贝的数据
*/
export function deepClone(data: any) {
let stack = [];
let cloned;
if (Array.isArray(data)) {
cloned = [];
} else if (typeof data === "object" && data !== null) {
cloned = {};
} else {
return data;
}
stack.push({
original: data,
copy: cloned
});
while (stack.length > 0) {
let current: any = stack.pop();
let original = current.original;
let copy = current.copy;
for (let key in original) {
if (original.hasOwnProperty(key)) {
let value = original[key];
if (typeof value === "object" && value !== null) {
copy[key] = Array.isArray(value) ? [] : {};
stack.push({
original: value,
copy: copy[key]
});
} else {
copy[key] = value;
}
}
}
}
return cloned;
}
/**
* 将扁平路由组装成树形结构
* @param {array} nodes 扁平数组
* @returns 树形结构
*/
export const buildTreeOptimized = (nodes: Menu.MenuOptions[]) => {
const nodeMap = new Map(); // 哈希表存储所有节点
const roots = []; // 存储顶层节点
const duplicates = new Set(); // 检测重复ID
// 第一次遍历: 注册所有节点 & 检测重复
for (const node of nodes) {
const id = node.id;
// 循环引用检测
if (node.id === node.parentId) {
throw new Error(`循环引用: ${node.id} -> ${node.parentId}`);
}
// 重复ID检测
if (nodeMap.has(id)) {
duplicates.add(id);
continue;
}
// 初始化子节点为null,这里children必须得是null,因为arco.design的展开列表组件根据数组判断是否显示展开按钮,哪怕是空数组也会显示展开按钮
node.children = null;
nodeMap.set(id, node);
}
// 输出重复警告
if (duplicates.size > 0) {
console.warn(`检测到重复ID: ${Array.from(duplicates).join(", ")}`);
}
// 第二次遍历: 构建树结构
for (const node of nodes) {
const { parentId } = node;
// 跳过已处理的重复节点
if (duplicates.has(node.id)) continue;
if (parentId === "0") {
roots.push(node); // 顶层节点
} else if (parentId) {
const parent = nodeMap.get(parentId);
if (parent) {
// 初始化父节点的children为数组(若为null)
if (parent.children === null) {
parent.children = [];
}
parent.children.push(node);
}
} else {
console.warn(`独立节点 ${node.id}: parentId为空`);
}
}
return roots;
};
import Mock from "mockjs";
/** 返回成功数据 */
export const resultSuccess = (data: unknown) => {
return Mock.mock({
code: 200,
data,
message: "请求成功",
success: true
});
};
/** 返回失败数据 */
export const resultError = (data: unknown, message: string, code = 500) => {
return Mock.mock({
code,
data,
message,
success: false
});
};
/**
* 路由树递归排序
* 1、先给当前层排序
* 2、若当前层有children则递归排序
* @param {array} tree 根据角色权限过滤后的路由树
* @returns 返回排序之后的树
*/
export const treeSort = (tree: Menu.MenuOptions[]) => {
if (!tree || tree.length == 0) return [];
tree.sort((a: Menu.MenuOptions, b: Menu.MenuOptions) => {
// a和b都是undefined则相等
if (a.meta.sort != 0 && !a.meta.sort && b.meta.sort != 0 && !b.meta.sort) {
return 0;
}
// a是undefined则a被排在b之后
if (a.meta.sort != 0 && !a.meta.sort) return 1;
// b是undefined则b被排在a之后
if (b.meta.sort != 0 && !b.meta.sort) return -1;
return a.meta.sort - b.meta.sort;
});
// 深层递归
return tree.map((item: any) => {
if (item?.children?.length > 0) {
item.children = treeSort(item.children);
}
return item;
});
};
/**
* 过滤路由树,返回有权限的树
* 1、根据角色权限过滤原始路由树
* 2、过滤禁用的菜单,该菜单是不可访问的,直接去掉
* @param {array} tree 根据角色权限过滤原始路由树
* @returns 返回有权限的树
*/
export const filterByDisable = (tree: any, userRoles: Array<string>) => {
return tree.filter((item: any) => {
// 过滤角色权限
if (item?.meta?.roles) {
if (!roleBase(item.meta.roles, userRoles)) return false;
}
// 过滤是否禁用
if (item?.meta?.disable) return false;
return true;
});
};
/**
* 校验该角色是否有路由权限
* @param {array} roles 路由的角色权限
* @returns 是否有权限 true是 false否
*/
export const roleBase = (roles: Array<string>, userRoles: Array<string>) => {
// 如果是admin则直接放行
if (userRoles.includes("admin")) return true;
// 否则判断权限
return userRoles.some((item: string) => roles.includes(item));
};
/**
* 深拷贝
* @param { string } data 需要深拷贝的数据
* @returns 深拷贝的数据
*/
export function deepClone(data: any) {
let stack = [];
let cloned;
if (Array.isArray(data)) {
cloned = [];
} else if (typeof data === "object" && data !== null) {
cloned = {};
} else {
return data;
}
stack.push({
original: data,
copy: cloned
});
while (stack.length > 0) {
let current: any = stack.pop();
let original = current.original;
let copy = current.copy;
for (let key in original) {
if (original.hasOwnProperty(key)) {
let value = original[key];
if (typeof value === "object" && value !== null) {
copy[key] = Array.isArray(value) ? [] : {};
stack.push({
original: value,
copy: copy[key]
});
} else {
copy[key] = value;
}
}
}
}
return cloned;
}
/**
* 将扁平路由组装成树形结构
* @param {array} nodes 扁平数组
* @returns 树形结构
*/
export const buildTreeOptimized = (nodes: Menu.MenuOptions[]) => {
const nodeMap = new Map(); // 哈希表存储所有节点
const roots = []; // 存储顶层节点
const duplicates = new Set(); // 检测重复ID
// 第一次遍历: 注册所有节点 & 检测重复
for (const node of nodes) {
const id = node.id;
// 循环引用检测
if (node.id === node.parentId) {
throw new Error(`循环引用: ${node.id} -> ${node.parentId}`);
}
// 重复ID检测
if (nodeMap.has(id)) {
duplicates.add(id);
continue;
}
// 初始化子节点为null,这里children必须得是null,因为arco.design的展开列表组件根据数组判断是否显示展开按钮,哪怕是空数组也会显示展开按钮
node.children = null;
nodeMap.set(id, node);
}
// 输出重复警告
if (duplicates.size > 0) {
console.warn(`检测到重复ID: ${Array.from(duplicates).join(", ")}`);
}
// 第二次遍历: 构建树结构
for (const node of nodes) {
const { parentId } = node;
// 跳过已处理的重复节点
if (duplicates.has(node.id)) continue;
if (parentId === "0") {
roots.push(node); // 顶层节点
} else if (parentId) {
const parent = nodeMap.get(parentId);
if (parent) {
// 初始化父节点的children为数组(若为null)
if (parent.children === null) {
parent.children = [];
}
parent.children.push(node);
}
} else {
console.warn(`独立节点 ${node.id}: parentId为空`);
}
}
return roots;
};
+194 -194
View File
@@ -1,194 +1,194 @@
import type { MockMethod } from "vite-plugin-mock";
import { resultSuccess } from "../_utils";
export default [
{
url: "/mock/document-library/tree",
method: "get",
timeout: 500,
response: () => {
let list = [
{
title: "总公司",
key: "0-0",
children: [
{
title: "行政部门",
key: "0-0-0",
children: [
{
title: "人力资源部",
key: "0-0-0-0",
children: [{ title: "员工出差申请表", key: "0-0-0-0-0" }]
},
{
title: "财务部",
key: "0-0-0-1",
children: [{ title: "行政费用预算分析", key: "0-0-0-0-1" }]
},
{
title: "法务部",
key: "0-0-0-2",
children: [{ title: "公司章程", key: "0-0-0-0-2" }]
},
{ title: "行政工作计划", key: "0-0-0-3" },
{ title: "会议室预订统计", key: "0-0-0-4" },
{ title: "月度工作总结", key: "0-0-0-5" }
]
},
{
title: "业务部门",
key: "0-0-1",
children: [
{ title: "客户反馈集锦", key: "0-0-1-0" },
{ title: "市场分析报告-季度", key: "0-0-1-1" }
]
},
{
title: "技术部门",
key: "0-0-2",
children: [
{ title: "代码审查记录", key: "0-0-2-0" },
{ title: "数据库优化方案", key: "0-0-2-1" },
{ title: "技术支持工单", key: "0-0-2-2" },
{ title: "安全漏洞扫描报告", key: "0-0-2-3" },
{ title: "系统性能调优总结", key: "0-0-2-4" },
{ title: "软件版本发布计划", key: "0-0-2-5" },
{ title: "技术培训材料", key: "0-0-2-6" },
{ title: "技术文档更新计划", key: "0-0-2-7" }
]
},
{
title: "后勤部门",
key: "0-0-3",
children: [
{ title: "设施维护报告", key: "0-0-3-0" },
{ title: "物流运输安排", key: "0-0-3-1" },
{ title: "仓库库存清单", key: "0-0-3-2" },
{ title: "办公室布局设计", key: "0-0-3-3" },
{ title: "设备采购申请表", key: "0-0-3-4" },
{ title: "食品安全检查记录", key: "0-0-3-5" }
]
}
]
}
];
return resultSuccess(list);
}
},
{
url: "/mock/document-library/table",
method: "get",
timeout: 500,
response: () => {
let list = [
{
key: "1",
source: "bilibili",
sourceSvg: "bilibili",
sourceType: "分享",
flow: "5015",
percent: "75",
status: 1,
createTime: "2024-05-27 09:00:00"
},
{
key: "2",
source: "微信",
sourceSvg: "wechat",
sourceType: "分享",
flow: "3217",
percent: "60",
status: 0,
createTime: "2024-05-26 15:30:00"
},
{
key: "3",
source: "QQ音乐",
sourceSvg: "QQ音乐",
sourceType: "搜索",
flow: "1343",
percent: "55",
status: 1,
createTime: "2024-05-25 12:45:00"
},
{
key: "4",
source: "百度",
sourceSvg: "百度",
sourceType: "搜索",
flow: "1235",
percent: "20",
status: 0,
createTime: "2024-05-24 11:20:00"
},
{
key: "5",
source: "优酷",
sourceSvg: "优酷",
sourceType: "首页推荐",
flow: "3456",
percent: "20",
status: 1,
createTime: "2024-05-23 14:10:00"
},
{
key: "6",
source: "网易云音乐",
sourceSvg: "网易云音乐",
sourceType: "每日一推",
flow: "5873",
percent: "30",
status: 0,
createTime: "2024-05-22 10:05:00"
},
{
key: "7",
source: "抖音",
sourceSvg: "抖音",
sourceType: "自然",
flow: "5465",
percent: "86",
status: 1,
createTime: "2024-05-21 08:45:00"
},
{
key: "8",
source: "西瓜视频",
sourceSvg: "西瓜视频",
sourceType: "搜索",
flow: "4642",
percent: "45",
status: 0,
createTime: "2024-05-20 16:30:00"
},
{
key: "9",
source: "微博",
sourceSvg: "微博",
sourceType: "搜索",
flow: "2375",
percent: "60",
status: 1,
createTime: "2024-05-19 09:20:00"
},
{
key: "10",
source: "豆瓣",
sourceSvg: "豆瓣",
sourceType: "搜索",
flow: "2465",
percent: "40",
status: 0,
createTime: "2024-05-18 13:55:00"
}
];
let data = {
list,
total: list.length
};
return resultSuccess(data);
}
}
] as MockMethod[];
import type { MockMethod } from "vite-plugin-mock";
import { resultSuccess } from "../_utils";
export default [
{
url: "/mock/document-library/tree",
method: "get",
timeout: 500,
response: () => {
let list = [
{
title: "总公司",
key: "0-0",
children: [
{
title: "行政部门",
key: "0-0-0",
children: [
{
title: "人力资源部",
key: "0-0-0-0",
children: [{ title: "员工出差申请表", key: "0-0-0-0-0" }]
},
{
title: "财务部",
key: "0-0-0-1",
children: [{ title: "行政费用预算分析", key: "0-0-0-0-1" }]
},
{
title: "法务部",
key: "0-0-0-2",
children: [{ title: "公司章程", key: "0-0-0-0-2" }]
},
{ title: "行政工作计划", key: "0-0-0-3" },
{ title: "会议室预订统计", key: "0-0-0-4" },
{ title: "月度工作总结", key: "0-0-0-5" }
]
},
{
title: "业务部门",
key: "0-0-1",
children: [
{ title: "客户反馈集锦", key: "0-0-1-0" },
{ title: "市场分析报告-季度", key: "0-0-1-1" }
]
},
{
title: "技术部门",
key: "0-0-2",
children: [
{ title: "代码审查记录", key: "0-0-2-0" },
{ title: "数据库优化方案", key: "0-0-2-1" },
{ title: "技术支持工单", key: "0-0-2-2" },
{ title: "安全漏洞扫描报告", key: "0-0-2-3" },
{ title: "系统性能调优总结", key: "0-0-2-4" },
{ title: "软件版本发布计划", key: "0-0-2-5" },
{ title: "技术培训材料", key: "0-0-2-6" },
{ title: "技术文档更新计划", key: "0-0-2-7" }
]
},
{
title: "后勤部门",
key: "0-0-3",
children: [
{ title: "设施维护报告", key: "0-0-3-0" },
{ title: "物流运输安排", key: "0-0-3-1" },
{ title: "仓库库存清单", key: "0-0-3-2" },
{ title: "办公室布局设计", key: "0-0-3-3" },
{ title: "设备采购申请表", key: "0-0-3-4" },
{ title: "食品安全检查记录", key: "0-0-3-5" }
]
}
]
}
];
return resultSuccess(list);
}
},
{
url: "/mock/document-library/table",
method: "get",
timeout: 500,
response: () => {
let list = [
{
key: "1",
source: "bilibili",
sourceSvg: "bilibili",
sourceType: "分享",
flow: "5015",
percent: "75",
status: 1,
createTime: "2024-05-27 09:00:00"
},
{
key: "2",
source: "微信",
sourceSvg: "wechat",
sourceType: "分享",
flow: "3217",
percent: "60",
status: 0,
createTime: "2024-05-26 15:30:00"
},
{
key: "3",
source: "QQ音乐",
sourceSvg: "QQ音乐",
sourceType: "搜索",
flow: "1343",
percent: "55",
status: 1,
createTime: "2024-05-25 12:45:00"
},
{
key: "4",
source: "百度",
sourceSvg: "百度",
sourceType: "搜索",
flow: "1235",
percent: "20",
status: 0,
createTime: "2024-05-24 11:20:00"
},
{
key: "5",
source: "优酷",
sourceSvg: "优酷",
sourceType: "首页推荐",
flow: "3456",
percent: "20",
status: 1,
createTime: "2024-05-23 14:10:00"
},
{
key: "6",
source: "网易云音乐",
sourceSvg: "网易云音乐",
sourceType: "每日一推",
flow: "5873",
percent: "30",
status: 0,
createTime: "2024-05-22 10:05:00"
},
{
key: "7",
source: "抖音",
sourceSvg: "抖音",
sourceType: "自然",
flow: "5465",
percent: "86",
status: 1,
createTime: "2024-05-21 08:45:00"
},
{
key: "8",
source: "西瓜视频",
sourceSvg: "西瓜视频",
sourceType: "搜索",
flow: "4642",
percent: "45",
status: 0,
createTime: "2024-05-20 16:30:00"
},
{
key: "9",
source: "微博",
sourceSvg: "微博",
sourceType: "搜索",
flow: "2375",
percent: "60",
status: 1,
createTime: "2024-05-19 09:20:00"
},
{
key: "10",
source: "豆瓣",
sourceSvg: "豆瓣",
sourceType: "搜索",
flow: "2465",
percent: "40",
status: 0,
createTime: "2024-05-18 13:55:00"
}
];
let data = {
list,
total: list.length
};
return resultSuccess(data);
}
}
] as MockMethod[];
+12 -12
View File
@@ -1,12 +1,12 @@
import { createProdMockServer } from "vite-plugin-mock/es/createProdMockServer";
import testModule from "./test/index";
import userModule from "./user/index";
import systemModule from "./system/index";
import fileModule from "./file/index";
import tableModule from "./table/index";
import monitorModule from "./monitor/index";
export function setupProdMockServer() {
createProdMockServer([...testModule, ...userModule, ...systemModule, ...fileModule, ...tableModule, ...monitorModule]);
}
import { createProdMockServer } from "vite-plugin-mock/es/createProdMockServer";
import testModule from "./test/index";
import userModule from "./user/index";
import systemModule from "./system/index";
import fileModule from "./file/index";
import tableModule from "./table/index";
import monitorModule from "./monitor/index";
export function setupProdMockServer() {
createProdMockServer([...testModule, ...userModule, ...systemModule, ...fileModule, ...tableModule, ...monitorModule]);
}
+4 -4
View File
@@ -1,4 +1,4 @@
import menu from "./menu";
import system from "./system";
export default [...menu, ...system];
import menu from "./menu";
import system from "./system";
export default [...menu, ...system];
+74 -74
View File
@@ -1,74 +1,74 @@
import type { MockMethod } from "vite-plugin-mock";
import { deepClone, filterByDisable, buildTreeOptimized, treeSort, resultSuccess } from "../_utils";
import { systemMenu, permissionData } from "../_data/system_menu";
/**
* 初始化
* 后端接口需要做的事情:
* 1、根据token判断角色
* 2、过滤扁平路由,根据角色过滤权限和非禁用的节点
* 3、将扁平路由转换为树结构
* 4、路由树排序
* 5、返回路由树
*
* 前端调用接口拿到路由数据后:
* 1、将模块设置为真实模块
* 2、存储路由树,用于生成菜单
* 3、根据树生成一维路由数组
* 4、动态添加路由
* 5、缓存一维路由
*/
/**
* post请求body,get请求query
* /mock/menu/getRouters 获取路由数据
* /mock/menu/getMenuList 获取菜单列表数据-菜单管理
* /mock/menu/getUserPermission 根据角色获取权限数据
* /mock/menu/getPermission 获取权限数据
*/
export default [
{
url: "/mock/menu/getRouters",
method: "get",
timeout: 300,
response: ({ headers }: any) => {
let token = headers.authorization;
// 根据token或登录账号判断是什么角色,这里模拟两个角色,admin、common
let userRoles = token === "Admin-Token" ? ["admin"] : ["common"];
const originMenu: any = deepClone(systemMenu);
// 1. 过滤扁平路由,根据角色返回有权限且非禁用的节点
const survivalTree = filterByDisable(originMenu, userRoles);
// 2. 将扁平路由转换为树结构
// 2. 给路由树排序
// 3. 返回路由树
return resultSuccess(treeSort(buildTreeOptimized(survivalTree)));
}
},
{
url: "/mock/menu/getMenuList",
method: "get",
timeout: 300,
response: () => {
// 菜单管理这里需要查看到所有菜单,无需判断角色权限、禁用菜单
// 将扁平路由和权限菜单合并
const originMenu: any = [...deepClone(systemMenu), ...deepClone(permissionData)];
// 1. 将扁平路由转换为树结构
// 2. 给路由树排序
// 3. 返回路由树
return resultSuccess(treeSort(buildTreeOptimized(originMenu)));
}
},
{
url: "/mock/menu/getUserPermission",
method: "get",
timeout: 300,
response: ({ query }: any) => {
let { role } = query;
// 将扁平路由和权限菜单合并
const originMenu: any = [...deepClone(systemMenu), ...deepClone(permissionData)];
// 根据角色过滤id
let idList = originMenu.filter((item: any) => item.meta.roles.includes(role)).map((item: any) => item.id);
return resultSuccess(idList);
}
}
] as MockMethod[];
import type { MockMethod } from "vite-plugin-mock";
import { deepClone, filterByDisable, buildTreeOptimized, treeSort, resultSuccess } from "../_utils";
import { systemMenu, permissionData } from "../_data/system_menu";
/**
* 初始化
* 后端接口需要做的事情:
* 1、根据token判断角色
* 2、过滤扁平路由,根据角色过滤权限和非禁用的节点
* 3、将扁平路由转换为树结构
* 4、路由树排序
* 5、返回路由树
*
* 前端调用接口拿到路由数据后:
* 1、将模块设置为真实模块
* 2、存储路由树,用于生成菜单
* 3、根据树生成一维路由数组
* 4、动态添加路由
* 5、缓存一维路由
*/
/**
* post请求body,get请求query
* /mock/menu/getRouters 获取路由数据
* /mock/menu/getMenuList 获取菜单列表数据-菜单管理
* /mock/menu/getUserPermission 根据角色获取权限数据
* /mock/menu/getPermission 获取权限数据
*/
export default [
{
url: "/mock/menu/getRouters",
method: "get",
timeout: 300,
response: ({ headers }: any) => {
let token = headers.authorization;
// 根据token或登录账号判断是什么角色,这里模拟两个角色,admin、common
let userRoles = token === "Admin-Token" ? ["admin"] : ["common"];
const originMenu: any = deepClone(systemMenu);
// 1. 过滤扁平路由,根据角色返回有权限且非禁用的节点
const survivalTree = filterByDisable(originMenu, userRoles);
// 2. 将扁平路由转换为树结构
// 2. 给路由树排序
// 3. 返回路由树
return resultSuccess(treeSort(buildTreeOptimized(survivalTree)));
}
},
{
url: "/mock/menu/getMenuList",
method: "get",
timeout: 300,
response: () => {
// 菜单管理这里需要查看到所有菜单,无需判断角色权限、禁用菜单
// 将扁平路由和权限菜单合并
const originMenu: any = [...deepClone(systemMenu), ...deepClone(permissionData)];
// 1. 将扁平路由转换为树结构
// 2. 给路由树排序
// 3. 返回路由树
return resultSuccess(treeSort(buildTreeOptimized(originMenu)));
}
},
{
url: "/mock/menu/getUserPermission",
method: "get",
timeout: 300,
response: ({ query }: any) => {
let { role } = query;
// 将扁平路由和权限菜单合并
const originMenu: any = [...deepClone(systemMenu), ...deepClone(permissionData)];
// 根据角色过滤id
let idList = originMenu.filter((item: any) => item.meta.roles.includes(role)).map((item: any) => item.id);
return resultSuccess(idList);
}
}
] as MockMethod[];
+233 -233
View File
@@ -1,233 +1,233 @@
import type { MockMethod } from "vite-plugin-mock";
import { resultSuccess } from "../_utils";
export default [
{
url: "/mock/common-table/list",
method: "get",
timeout: 500,
response: () => {
let list = [
{
key: "1",
name: "陈思源",
avatar: "陈",
phone: "13812345678",
email: "zhangsan@example.com",
address: "北京市朝阳区",
status: 1,
createTime: "2024-05-27 09:00:00"
},
{
key: "2",
name: "李婉娴",
avatar: "李",
phone: "13987654321",
email: "lisi@example.com",
address: "上海市浦东新区",
status: 0,
createTime: "2024-05-26 15:30:00"
},
{
key: "3",
name: "王雨菲",
avatar: "王",
phone: "13666666666",
email: "wangwu@example.com",
address: "广州市天河区",
status: 1,
createTime: "2024-05-25 12:45:00"
},
{
key: "4",
name: "张晨曦",
avatar: "张",
phone: "13788888888",
email: "zhaoliu@example.com",
address: "深圳市福田区",
status: 0,
createTime: "2024-05-24 11:20:00"
},
{
key: "5",
name: "赵梦琪",
avatar: "赵",
phone: "13599999999",
email: "qianqi@example.com",
address: "成都市锦江区",
status: 1,
createTime: "2024-05-23 14:10:00"
},
{
key: "6",
name: "刘昊然",
avatar: "刘",
phone: "13377777777",
email: "sunba@example.com",
address: "杭州市西湖区",
status: 0,
createTime: "2024-05-22 10:05:00"
},
{
key: "7",
name: "孙梦洁",
avatar: "孙",
phone: "13266666666",
email: "zhoujiu@example.com",
address: "南京市鼓楼区",
status: 1,
createTime: "2024-05-21 08:45:00"
},
{
key: "8",
name: "黄俊杰",
avatar: "黄",
phone: "13155555555",
email: "wushi@example.com",
address: "重庆市渝中区",
status: 0,
createTime: "2024-05-20 16:30:00"
},
{
key: "9",
name: "周雨萱",
avatar: "周",
phone: "13044444444",
email: "zhengshiyi@example.com",
address: "武汉市江汉区",
status: 1,
createTime: "2024-05-19 09:20:00"
},
{
key: "10",
name: "韩雪儿",
avatar: "韩",
phone: "13933333333",
email: "kongshier@example.com",
address: "西安市雁塔区",
status: 0,
createTime: "2024-05-18 13:55:00"
}
];
let data = {
list,
total: list.length
};
return resultSuccess(data);
}
},
{
url: "/mock/custom-table/list",
method: "get",
timeout: 500,
response: () => {
let list = [
{
key: "1",
serial: "57",
name: "WEIJEIWGSDG",
content: "图文",
searchType: "阅读量",
contentSize: 3700,
status: 1,
createTime: "2024-05-27 09:00:00"
},
{
key: "2",
serial: "58",
name: "DHDWEH",
content: "图文",
searchType: "阅读量",
contentSize: 3700,
status: 0,
createTime: "2024-05-26 15:30:00"
},
{
key: "3",
serial: "59",
name: "SHEHWAE",
content: "视频",
searchType: "播放量",
contentSize: 2500,
status: 1,
createTime: "2024-05-25 12:45:00"
},
{
key: "4",
serial: "60",
name: "WEHJUK",
content: "视频",
searchType: "播放量",
contentSize: 2500,
status: 0,
createTime: "2024-05-24 11:20:00"
},
{
key: "5",
serial: "61",
name: "EYTUJDGSD",
content: "音频",
searchType: "播放量",
contentSize: 2500,
status: 1,
createTime: "2024-05-23 14:10:00"
},
{
key: "6",
serial: "62",
name: "RTIFSDF",
content: "图文",
searchType: "阅读量",
contentSize: 3700,
status: 0,
createTime: "2024-05-22 10:05:00"
},
{
key: "7",
serial: "63",
name: "OIKSHHFD",
content: "图文",
searchType: "阅读量",
contentSize: 3700,
status: 1,
createTime: "2024-05-21 08:45:00"
},
{
key: "8",
serial: "64",
name: "QEUHRKO",
content: "视频",
searchType: "播放量",
contentSize: 2500,
status: 0,
createTime: "2024-05-20 16:30:00"
},
{
key: "9",
serial: "65",
name: "JSGSDRI",
content: "视频",
searchType: "播放量",
contentSize: 2300,
status: 1,
createTime: "2024-05-19 09:20:00"
},
{
key: "10",
serial: "66",
name: "AOUSTHREGG",
content: "音频",
searchType: "播放量",
contentSize: 2300,
status: 0,
createTime: "2024-05-18 13:55:00"
}
];
let data = {
list,
total: list.length
};
return resultSuccess(data);
}
}
] as MockMethod[];
import type { MockMethod } from "vite-plugin-mock";
import { resultSuccess } from "../_utils";
export default [
{
url: "/mock/common-table/list",
method: "get",
timeout: 500,
response: () => {
let list = [
{
key: "1",
name: "陈思源",
avatar: "陈",
phone: "13812345678",
email: "zhangsan@example.com",
address: "北京市朝阳区",
status: 1,
createTime: "2024-05-27 09:00:00"
},
{
key: "2",
name: "李婉娴",
avatar: "李",
phone: "13987654321",
email: "lisi@example.com",
address: "上海市浦东新区",
status: 0,
createTime: "2024-05-26 15:30:00"
},
{
key: "3",
name: "王雨菲",
avatar: "王",
phone: "13666666666",
email: "wangwu@example.com",
address: "广州市天河区",
status: 1,
createTime: "2024-05-25 12:45:00"
},
{
key: "4",
name: "张晨曦",
avatar: "张",
phone: "13788888888",
email: "zhaoliu@example.com",
address: "深圳市福田区",
status: 0,
createTime: "2024-05-24 11:20:00"
},
{
key: "5",
name: "赵梦琪",
avatar: "赵",
phone: "13599999999",
email: "qianqi@example.com",
address: "成都市锦江区",
status: 1,
createTime: "2024-05-23 14:10:00"
},
{
key: "6",
name: "刘昊然",
avatar: "刘",
phone: "13377777777",
email: "sunba@example.com",
address: "杭州市西湖区",
status: 0,
createTime: "2024-05-22 10:05:00"
},
{
key: "7",
name: "孙梦洁",
avatar: "孙",
phone: "13266666666",
email: "zhoujiu@example.com",
address: "南京市鼓楼区",
status: 1,
createTime: "2024-05-21 08:45:00"
},
{
key: "8",
name: "黄俊杰",
avatar: "黄",
phone: "13155555555",
email: "wushi@example.com",
address: "重庆市渝中区",
status: 0,
createTime: "2024-05-20 16:30:00"
},
{
key: "9",
name: "周雨萱",
avatar: "周",
phone: "13044444444",
email: "zhengshiyi@example.com",
address: "武汉市江汉区",
status: 1,
createTime: "2024-05-19 09:20:00"
},
{
key: "10",
name: "韩雪儿",
avatar: "韩",
phone: "13933333333",
email: "kongshier@example.com",
address: "西安市雁塔区",
status: 0,
createTime: "2024-05-18 13:55:00"
}
];
let data = {
list,
total: list.length
};
return resultSuccess(data);
}
},
{
url: "/mock/custom-table/list",
method: "get",
timeout: 500,
response: () => {
let list = [
{
key: "1",
serial: "57",
name: "WEIJEIWGSDG",
content: "图文",
searchType: "阅读量",
contentSize: 3700,
status: 1,
createTime: "2024-05-27 09:00:00"
},
{
key: "2",
serial: "58",
name: "DHDWEH",
content: "图文",
searchType: "阅读量",
contentSize: 3700,
status: 0,
createTime: "2024-05-26 15:30:00"
},
{
key: "3",
serial: "59",
name: "SHEHWAE",
content: "视频",
searchType: "播放量",
contentSize: 2500,
status: 1,
createTime: "2024-05-25 12:45:00"
},
{
key: "4",
serial: "60",
name: "WEHJUK",
content: "视频",
searchType: "播放量",
contentSize: 2500,
status: 0,
createTime: "2024-05-24 11:20:00"
},
{
key: "5",
serial: "61",
name: "EYTUJDGSD",
content: "音频",
searchType: "播放量",
contentSize: 2500,
status: 1,
createTime: "2024-05-23 14:10:00"
},
{
key: "6",
serial: "62",
name: "RTIFSDF",
content: "图文",
searchType: "阅读量",
contentSize: 3700,
status: 0,
createTime: "2024-05-22 10:05:00"
},
{
key: "7",
serial: "63",
name: "OIKSHHFD",
content: "图文",
searchType: "阅读量",
contentSize: 3700,
status: 1,
createTime: "2024-05-21 08:45:00"
},
{
key: "8",
serial: "64",
name: "QEUHRKO",
content: "视频",
searchType: "播放量",
contentSize: 2500,
status: 0,
createTime: "2024-05-20 16:30:00"
},
{
key: "9",
serial: "65",
name: "JSGSDRI",
content: "视频",
searchType: "播放量",
contentSize: 2300,
status: 1,
createTime: "2024-05-19 09:20:00"
},
{
key: "10",
serial: "66",
name: "AOUSTHREGG",
content: "音频",
searchType: "播放量",
contentSize: 2300,
status: 0,
createTime: "2024-05-18 13:55:00"
}
];
let data = {
list,
total: list.length
};
return resultSuccess(data);
}
}
] as MockMethod[];
+21 -21
View File
@@ -1,21 +1,21 @@
import type { MockMethod } from "vite-plugin-mock";
import { resultSuccess, resultError } from "../_utils";
export default [
{
url: "/mock/test/success",
method: "get",
timeout: 300,
response: () => {
return resultSuccess("SnowAdmin开源免费,Welcome!");
}
},
{
url: "/mock/test/fail",
method: "get",
timeout: 300,
response: () => {
return resultError(null, "模拟mock数据出错", 500);
}
}
] as MockMethod[];
import type { MockMethod } from "vite-plugin-mock";
import { resultSuccess, resultError } from "../_utils";
export default [
{
url: "/mock/test/success",
method: "get",
timeout: 300,
response: () => {
return resultSuccess("SnowAdmin开源免费,Welcome!");
}
},
{
url: "/mock/test/fail",
method: "get",
timeout: 300,
response: () => {
return resultError(null, "模拟mock数据出错", 500);
}
}
] as MockMethod[];
+76 -76
View File
@@ -1,76 +1,76 @@
import type { MockMethod } from "vite-plugin-mock";
import { resultSuccess, resultError, deepClone } from "../_utils";
import { accountData } from "../_data/system_data";
import { permissionData } from "../_data/system_menu";
import { roleData } from "../_data/system_data";
/**
* post请求body,get请求query
* /mock/login 用户登录
* /mock/user/getUserInfo 获取用户信息
*/
export default [
{
url: "/mock/login",
method: "post",
timeout: 300,
response: ({ body }: any) => {
let { username, password } = body;
// 根据登录账号返回token,这里模拟两个账号
// 1、admin账号
// 2、common账号
if (username === "admin" && password === "123456") {
return resultSuccess({ token: "Admin-Token" });
}
if (username === "common" && password === "123456") {
return resultSuccess({ token: "Common-Token" });
}
return resultError(null, "账号或者密码错误", 500);
}
},
{
url: "/mock/user/getUserInfo",
method: "get",
timeout: 300,
response: ({ headers, query }: any) => {
let data: any = {
user: {}, // 账户信息
roles: [], // 角色
permissions: [] // 权限
};
let account = deepClone(accountData);
// 传入id则通过id匹配,否则通过token匹配
if (query.id) {
data.user = account.find((item: any) => item.id == query.id);
} else {
// 1、拿账户信息
if (headers.authorization == "Admin-Token") {
// 管理员账户
data.user = account.find((item: any) => item.id == 1);
} else {
// 普通账户
data.user = account.find((item: any) => item.id == 2);
}
}
// 2、根据账户拿角色信息
let roleInfo = roleData.filter((item: any) => data.user.roles.includes(item.code));
data.user.roles = roleInfo;
data.roles = roleInfo.map((item: any) => item.code);
// 3、拿权限信息
// 超级管理员
if (data.roles.includes("admin")) {
data.permissions = ["*:*:*"];
} else {
// 非admin账号则只拿对应角色的权限
let list = permissionData.filter((permission: any) => {
return data.roles.some((item: string) => permission.meta.roles.includes(item));
});
data.permissions = list.map(item => item.meta.permission);
}
return resultSuccess(data);
}
}
] as MockMethod[];
import type { MockMethod } from "vite-plugin-mock";
import { resultSuccess, resultError, deepClone } from "../_utils";
import { accountData } from "../_data/system_data";
import { permissionData } from "../_data/system_menu";
import { roleData } from "../_data/system_data";
/**
* post请求body,get请求query
* /mock/login 用户登录
* /mock/user/getUserInfo 获取用户信息
*/
export default [
{
url: "/mock/login",
method: "post",
timeout: 300,
response: ({ body }: any) => {
let { username, password } = body;
// 根据登录账号返回token,这里模拟两个账号
// 1、admin账号
// 2、common账号
if (username === "admin" && password === "123456") {
return resultSuccess({ token: "Admin-Token" });
}
if (username === "common" && password === "123456") {
return resultSuccess({ token: "Common-Token" });
}
return resultError(null, "账号或者密码错误", 500);
}
},
{
url: "/mock/user/getUserInfo",
method: "get",
timeout: 300,
response: ({ headers, query }: any) => {
let data: any = {
user: {}, // 账户信息
roles: [], // 角色
permissions: [] // 权限
};
let account = deepClone(accountData);
// 传入id则通过id匹配,否则通过token匹配
if (query.id) {
data.user = account.find((item: any) => item.id == query.id);
} else {
// 1、拿账户信息
if (headers.authorization == "Admin-Token") {
// 管理员账户
data.user = account.find((item: any) => item.id == 1);
} else {
// 普通账户
data.user = account.find((item: any) => item.id == 2);
}
}
// 2、根据账户拿角色信息
let roleInfo = roleData.filter((item: any) => data.user.roles.includes(item.code));
data.user.roles = roleInfo;
data.roles = roleInfo.map((item: any) => item.code);
// 3、拿权限信息
// 超级管理员
if (data.roles.includes("admin")) {
data.permissions = ["*:*:*"];
} else {
// 非admin账号则只拿对应角色的权限
let list = permissionData.filter((permission: any) => {
return data.roles.some((item: string) => permission.meta.roles.includes(item));
});
data.permissions = list.map(item => item.meta.permission);
}
return resultSuccess(data);
}
}
] as MockMethod[];
+109 -109
View File
@@ -1,109 +1,109 @@
import NProgress from "@/config/nprogress";
import pinia from "@/store/index";
import { createRouter, createWebHashHistory } from "vue-router";
import { staticRoutes, notFoundAndNoPower } from "@/router/route.ts";
import { currentlyRoute } from "@/router/route-output";
import { storeToRefs } from "pinia";
import { useUserInfoStore } from "@/store/modules/user-info";
import { useRouteConfigStore } from "@/store/modules/route-config";
import { useRoutingMethod } from "@/hooks/useRoutingMethod";
/**
* 创建vue的路由示例
* @method createRouter(options: RouterOptions): Router
* @link 参考:https://next.router.vuejs.org/zh/api/#createrouter
*/
const router = createRouter({
history: createWebHashHistory(),
/**
* 设置静态路由,其它的路由通过addRoute动态添加
* 1、staticRoutes登录页、layout页、默认页面('/')
* 2、notFoundAndNoPower 添加默认 401、500界面,防止提示 No match found for location with path 'xxx'
* 2、后端控制路由中也需要添加 notFoundAndNoPower 401、500界面
* 静态添加 notFoundAndNoPower 401、500界面将全屏显示
* 如果要 notFoundAndNoPower 在layout容器展示,则需要移除静态添加并将其添加到缓存路由树
*/
routes: [...staticRoutes, ...notFoundAndNoPower]
});
/**
* 路由加载前需要判断用户是否登录
* 1、去登录页,无token,放行
* 2、没有token,直接重定向到登录页
* 3、去登录页,有token,直接重定向到home页
* 4、去非登录页,有token,用户信息是否存在,有则放行,否则重新获取路由信息、初始化路由
* 注意:
* 全局routeTree不能持久化缓存
* 页面刷新会导致addRoute动态添加的路由失效,需要重新初始化路由
*/
router.beforeEach(async (to: any, _: any, next: any) => {
NProgress.start(); // 开启进度条
const store = useUserInfoStore(pinia);
const routeStore = useRouteConfigStore(pinia);
const { token } = storeToRefs(store);
const { routeTree } = storeToRefs(routeStore);
// console.log("去", to, "来自", from);
// next()内部加了path等于跳转指定路由会再次触发router.beforeEach,内部无参数等于放行,不会触发router.beforeEach
// 1、去登录页,无token,放行
if (to.path === "/login" && !token.value) return next();
// 2、没有token,直接重定向到登录页
if (!token.value) return next("/login");
// 3、去登录页,有token,直接重定向到home页
if (to.path === "/login" && token.value) {
// 项目内的跳转,处理跳转路由高亮
currentlyRoute(to);
return next("/home");
}
// 4、去非登录页,有token,用户信息是否存在,有则放行,否则重新获取路由信息、初始化路由
// 判断路由是否获取,先获取账号信息和路由信息,添加路由后再跳转(页面刷新时触发)
// 解决刷新页面404的问题
if (!routeTree.value.length) {
const routeStore = useRouteConfigStore(pinia);
try {
// 获取账号信息
await store.setAccount();
// 获取路由信息
await routeStore.initSetRouter();
// 判断是否是动态路由
const { isDynamicRoute } = useRoutingMethod();
if (isDynamicRoute(to.path)) {
return next({ name: to.name, params: to.params });
} else {
return next({ path: to.path, query: to.query });
}
} catch (error) {
console.error(error);
return next(false);
}
}
// 获取外链路由的处理函数
// 所有的路由正常放行,只不过额外判断是否是外链,如果是,则打开新窗口跳转外链
// 外链的页面依旧正常打开,只不过不会参与缓存与tabs显示,符合路由跳转的直觉
const { openExternalLinks } = useRoutingMethod();
// 处理外链跳转
openExternalLinks(to);
// 项目内的跳转,处理跳转路由高亮
currentlyRoute(to);
// 动态路由添加过走这里,直接放行
next();
});
// 路由跳转错误
router.onError((error: any) => {
NProgress.done();
console.warn("路由错误", error.message);
});
// 路由加载后
router.afterEach(() => {
NProgress.done();
});
export default router;
import NProgress from "@/config/nprogress";
import pinia from "@/store/index";
import { createRouter, createWebHashHistory } from "vue-router";
import { staticRoutes, notFoundAndNoPower } from "@/router/route.ts";
import { currentlyRoute } from "@/router/route-output";
import { storeToRefs } from "pinia";
import { useUserInfoStore } from "@/store/modules/user-info";
import { useRouteConfigStore } from "@/store/modules/route-config";
import { useRoutingMethod } from "@/hooks/useRoutingMethod";
/**
* 创建vue的路由示例
* @method createRouter(options: RouterOptions): Router
* @link 参考:https://next.router.vuejs.org/zh/api/#createrouter
*/
const router = createRouter({
history: createWebHashHistory(),
/**
* 设置静态路由,其它的路由通过addRoute动态添加
* 1、staticRoutes登录页、layout页、默认页面('/')
* 2、notFoundAndNoPower 添加默认 401、500界面,防止提示 No match found for location with path 'xxx'
* 2、后端控制路由中也需要添加 notFoundAndNoPower 401、500界面
* 静态添加 notFoundAndNoPower 401、500界面将全屏显示
* 如果要 notFoundAndNoPower 在layout容器展示,则需要移除静态添加并将其添加到缓存路由树
*/
routes: [...staticRoutes, ...notFoundAndNoPower]
});
/**
* 路由加载前需要判断用户是否登录
* 1、去登录页,无token,放行
* 2、没有token,直接重定向到登录页
* 3、去登录页,有token,直接重定向到home页
* 4、去非登录页,有token,用户信息是否存在,有则放行,否则重新获取路由信息、初始化路由
* 注意:
* 全局routeTree不能持久化缓存
* 页面刷新会导致addRoute动态添加的路由失效,需要重新初始化路由
*/
router.beforeEach(async (to: any, _: any, next: any) => {
NProgress.start(); // 开启进度条
const store = useUserInfoStore(pinia);
const routeStore = useRouteConfigStore(pinia);
const { token } = storeToRefs(store);
const { routeTree } = storeToRefs(routeStore);
// console.log("去", to, "来自", from);
// next()内部加了path等于跳转指定路由会再次触发router.beforeEach,内部无参数等于放行,不会触发router.beforeEach
// 1、去登录页,无token,放行
if (to.path === "/login" && !token.value) return next();
// 2、没有token,直接重定向到登录页
if (!token.value) return next("/login");
// 3、去登录页,有token,直接重定向到home页
if (to.path === "/login" && token.value) {
// 项目内的跳转,处理跳转路由高亮
currentlyRoute(to);
return next("/home");
}
// 4、去非登录页,有token,用户信息是否存在,有则放行,否则重新获取路由信息、初始化路由
// 判断路由是否获取,先获取账号信息和路由信息,添加路由后再跳转(页面刷新时触发)
// 解决刷新页面404的问题
if (!routeTree.value.length) {
const routeStore = useRouteConfigStore(pinia);
try {
// 获取账号信息
await store.setAccount();
// 获取路由信息
await routeStore.initSetRouter();
// 判断是否是动态路由
const { isDynamicRoute } = useRoutingMethod();
if (isDynamicRoute(to.path)) {
return next({ name: to.name, params: to.params });
} else {
return next({ path: to.path, query: to.query });
}
} catch (error) {
console.error(error);
return next(false);
}
}
// 获取外链路由的处理函数
// 所有的路由正常放行,只不过额外判断是否是外链,如果是,则打开新窗口跳转外链
// 外链的页面依旧正常打开,只不过不会参与缓存与tabs显示,符合路由跳转的直觉
const { openExternalLinks } = useRoutingMethod();
// 处理外链跳转
openExternalLinks(to);
// 项目内的跳转,处理跳转路由高亮
currentlyRoute(to);
// 动态路由添加过走这里,直接放行
next();
});
// 路由跳转错误
router.onError((error: any) => {
NProgress.done();
console.warn("路由错误", error.message);
});
// 路由加载后
router.afterEach(() => {
NProgress.done();
});
export default router;
+91 -91
View File
@@ -1,91 +1,91 @@
import pinia from "@/store/index";
import { storeToRefs } from "pinia";
import { useRouteConfigStore } from "@/store/modules/route-config";
import { useThemeConfig } from "@/store/modules/theme-config";
import { deepClone } from "@/utils/index";
import { arrayFlattened } from "@/utils/tree-tools";
/**
* 统一处理所有的路由跳转:当前路由高亮、tabs栏数据
* 处理项目内跳转,存入当前跳转路由和tabs标签栏数据
* menu和tabs以及手动刷新浏览器等功能只需要跳转即可,缓存和高亮的逻辑这边负责
* @param {any} current 需要跳转的路由和路由参数
*/
export const currentlyRoute = (current: any) => {
const route = deepCloneRoute(current);
const themeStore = useThemeConfig();
const { isTabs } = storeToRefs(themeStore);
const store = useRouteConfigStore(pinia);
const { tabsList, routeList } = storeToRefs(store);
// tabs无数据则默认添加首页
if (tabsList.value.length == 0 && routeList.value.length != 0) {
store.setTabs(routeList.value[0]);
}
// 存入当前路由-高亮
store.setCurrentRoute(route);
// 如果是外链路由则不做后续任何缓存操作,条件: 有外链 && 非内嵌
if (route.meta.link && !route.meta.iframe) return;
// 存入tabs栏数据,条件:开启tabs
if (isTabs.value && !route.meta.isFull) store.setTabs(route);
// 不缓存路由 || 不渲染tabs ,符合任意条件则不缓存路由
if (!route.meta.keepAlive || !isTabs.value) return;
store.setRoutePaths(route.path); // 缓存路由
};
/**
* 深拷贝路由,切断与原路由的联系,防止路由参数污染
* @param route 当前路由
* @returns 深拷贝后的路由
*/
export const deepCloneRoute = (route: any) => {
return deepClone({
path: route.fullPath,
name: route.name,
meta: route.meta,
query: route.query,
params: route.params
});
};
/**
* 模块替换,对路由中的模块进行转换
* @param {array} tree 过滤角色权限后的树
*/
export const moduleReplacement = (tree: any) => {
tree.forEach((item: any) => {
item.children && delete item.children;
moduleMatch(item);
});
return tree;
};
/**
* 模块匹配
* 1、导入 views 目录及其子目录下的所有 .vue 文件。
* 2、匹配views下的所有文件路径,将模块转换为按需引入的真实模块
* 3、未匹配上,不做处理
*/
// 匹配views里面所有的.vue文件
const modules = import.meta.glob("@/views/**/*.vue");
export const moduleMatch = (item: any) => {
// 匹配每个views文件夹下的文件路径
for (const key in modules) {
const dir = key.split("views/")[1].replace(".vue", "");
// 若匹配上,则替换真实模块
if (item.component === dir) {
// 按需引入modules
// 将模块的导入操作和实际使用操作解耦,使得我们可以在需要的时候才执行导入操作
item.component = () => modules[key]();
}
}
};
/**
* 路由树转一维数组
* @param {array} tree 路由树
* @returns 一维路由数组
*/
export function linearArray(tree: any) {
const nodes: any = deepClone(tree);
return arrayFlattened(nodes, "children");
}
import pinia from "@/store/index";
import { storeToRefs } from "pinia";
import { useRouteConfigStore } from "@/store/modules/route-config";
import { useThemeConfig } from "@/store/modules/theme-config";
import { deepClone } from "@/utils/index";
import { arrayFlattened } from "@/utils/tree-tools";
/**
* 统一处理所有的路由跳转:当前路由高亮、tabs栏数据
* 处理项目内跳转,存入当前跳转路由和tabs标签栏数据
* menu和tabs以及手动刷新浏览器等功能只需要跳转即可,缓存和高亮的逻辑这边负责
* @param {any} current 需要跳转的路由和路由参数
*/
export const currentlyRoute = (current: any) => {
const route = deepCloneRoute(current);
const themeStore = useThemeConfig();
const { isTabs } = storeToRefs(themeStore);
const store = useRouteConfigStore(pinia);
const { tabsList, routeList } = storeToRefs(store);
// tabs无数据则默认添加首页
if (tabsList.value.length == 0 && routeList.value.length != 0) {
store.setTabs(routeList.value[0]);
}
// 存入当前路由-高亮
store.setCurrentRoute(route);
// 如果是外链路由则不做后续任何缓存操作,条件: 有外链 && 非内嵌
if (route.meta.link && !route.meta.iframe) return;
// 存入tabs栏数据,条件:开启tabs
if (isTabs.value && !route.meta.isFull) store.setTabs(route);
// 不缓存路由 || 不渲染tabs ,符合任意条件则不缓存路由
if (!route.meta.keepAlive || !isTabs.value) return;
store.setRoutePaths(route.path); // 缓存路由
};
/**
* 深拷贝路由,切断与原路由的联系,防止路由参数污染
* @param route 当前路由
* @returns 深拷贝后的路由
*/
export const deepCloneRoute = (route: any) => {
return deepClone({
path: route.fullPath,
name: route.name,
meta: route.meta,
query: route.query,
params: route.params
});
};
/**
* 模块替换,对路由中的模块进行转换
* @param {array} tree 过滤角色权限后的树
*/
export const moduleReplacement = (tree: any) => {
tree.forEach((item: any) => {
item.children && delete item.children;
moduleMatch(item);
});
return tree;
};
/**
* 模块匹配
* 1、导入 views 目录及其子目录下的所有 .vue 文件。
* 2、匹配views下的所有文件路径,将模块转换为按需引入的真实模块
* 3、未匹配上,不做处理
*/
// 匹配views里面所有的.vue文件
const modules = import.meta.glob("@/views/**/*.vue");
export const moduleMatch = (item: any) => {
// 匹配每个views文件夹下的文件路径
for (const key in modules) {
const dir = key.split("views/")[1].replace(".vue", "");
// 若匹配上,则替换真实模块
if (item.component === dir) {
// 按需引入modules
// 将模块的导入操作和实际使用操作解耦,使得我们可以在需要的时候才执行导入操作
item.component = () => modules[key]();
}
}
};
/**
* 路由树转一维数组
* @param {array} tree 路由树
* @returns 一维路由数组
*/
export function linearArray(tree: any) {
const nodes: any = deepClone(tree);
return arrayFlattened(nodes, "children");
}
+90 -90
View File
@@ -1,90 +1,90 @@
import { HOME_PATH } from "@/config/index";
import Layout from "@/layout/index.vue";
/**
* 路由path路径与文件夹名称相同,找文件可以浏览器地址快速查找,方便定位文件
*
* 路由meta对象参数,我们通常将属性放到meta对象中
* meta: {
* title: 菜单栏以及 tabsView 栏、菜单搜索名称(国际化)
* hide: 是否隐藏此路由,不会显示在菜单树,可以访问
* disable: 是否停用,不会显示在菜单树,且不可访问
* keepAlive: 是否缓存组件状态
* affix: 是否固定在 tabsView 栏上
* link: 是否是超链接菜单,开启外链条件:1、 link:链接地址不为空 2、iframe: false
* iframe: 是否内嵌窗口,开启条件:1、iframe:true 2、link:链接地址不为空
* roles: 当前路由权限表示,取角色管理。路由控制显示、隐藏。 超级管理员:admin;普通角色:common
* icon: 菜单、tabsView 图标等
* svgIcon: svg图标
* sort: 菜单顺序
* }
*/
/**
* 静态路由 (默认路由)
* 此路由不要动,用于做静态路由定向,如果要添加路由,请在 `layout-children` 中添加
* @description 前端控制路由 直接改 mock/_data/system_menu 中的路由,后端控制则不需要
* @returns 返回路由菜单数据
*/
export const staticRoutes = [
{
path: "/",
redirect: HOME_PATH
},
{
path: "/login",
name: "login",
component: () => import("@/views/login/login.vue"),
meta: {
title: "login"
}
},
{
path: "/layout",
name: "layout",
redirect: HOME_PATH,
component: Layout, // 容器布局-顶层路由
// 二级路由-主要渲染页面
children: []
}
/**
* 提示:写在这里的为全屏界面,不建议写在这里非全屏界面,请写在 layout.children 路由数组中
*
*/
];
/**
* 定义401、404、500界面
* 401无权限
* 404页面不存在
* 500网络断开
* @link 参考:https://router.vuejs.org/zh/guide/essentials/history-mode.html#netlify
*/
export const notFoundAndNoPower = [
{
path: "/401", // 无权限,跳转401
name: "no-access",
component: () => import("@/views/error/401.vue"),
meta: {
title: "no-access",
hide: true
}
},
{
path: "/500", // 无网络-浏览器离线
name: "no-network",
component: () => import("@/views/error/500.vue"),
meta: {
title: "no-network",
hide: true
}
},
{
path: "/:path(.*)*", // 匹配任意路由,兜底,未找到页面的时候跳转该页面
name: "not-found",
component: () => import("@/views/error/404.vue"),
meta: {
title: "not-found",
hide: true
}
}
];
import { HOME_PATH } from "@/config/index";
import Layout from "@/layout/index.vue";
/**
* 路由path路径与文件夹名称相同,找文件可以浏览器地址快速查找,方便定位文件
*
* 路由meta对象参数,我们通常将属性放到meta对象中
* meta: {
* title: 菜单栏以及 tabsView 栏、菜单搜索名称(国际化)
* hide: 是否隐藏此路由,不会显示在菜单树,可以访问
* disable: 是否停用,不会显示在菜单树,且不可访问
* keepAlive: 是否缓存组件状态
* affix: 是否固定在 tabsView 栏上
* link: 是否是超链接菜单,开启外链条件:1、 link:链接地址不为空 2、iframe: false
* iframe: 是否内嵌窗口,开启条件:1、iframe:true 2、link:链接地址不为空
* roles: 当前路由权限表示,取角色管理。路由控制显示、隐藏。 超级管理员:admin;普通角色:common
* icon: 菜单、tabsView 图标等
* svgIcon: svg图标
* sort: 菜单顺序
* }
*/
/**
* 静态路由 (默认路由)
* 此路由不要动,用于做静态路由定向,如果要添加路由,请在 `layout-children` 中添加
* @description 前端控制路由 直接改 mock/_data/system_menu 中的路由,后端控制则不需要
* @returns 返回路由菜单数据
*/
export const staticRoutes = [
{
path: "/",
redirect: HOME_PATH
},
{
path: "/login",
name: "login",
component: () => import("@/views/login/login.vue"),
meta: {
title: "login"
}
},
{
path: "/layout",
name: "layout",
redirect: HOME_PATH,
component: Layout, // 容器布局-顶层路由
// 二级路由-主要渲染页面
children: []
}
/**
* 提示:写在这里的为全屏界面,不建议写在这里非全屏界面,请写在 layout.children 路由数组中
*
*/
];
/**
* 定义401、404、500界面
* 401无权限
* 404页面不存在
* 500网络断开
* @link 参考:https://router.vuejs.org/zh/guide/essentials/history-mode.html#netlify
*/
export const notFoundAndNoPower = [
{
path: "/401", // 无权限,跳转401
name: "no-access",
component: () => import("@/views/error/401.vue"),
meta: {
title: "no-access",
hide: true
}
},
{
path: "/500", // 无网络-浏览器离线
name: "no-network",
component: () => import("@/views/error/500.vue"),
meta: {
title: "no-network",
hide: true
}
},
{
path: "/:path(.*)*", // 匹配任意路由,兜底,未找到页面的时候跳转该页面
name: "not-found",
component: () => import("@/views/error/404.vue"),
meta: {
title: "not-found",
hide: true
}
}
];
+16 -16
View File
@@ -1,16 +1,16 @@
/**
* https://prazdevs.github.io/pinia-plugin-persistedstate/zh/guide/config.html
* @description: 持久化配置
* @param {string} key 存储的key
* @param {Array<string>} paths 需要持久化的字段
* @return {*}
*/
const persistedstateConfig = (key: string, paths?: Array<string>) => {
return {
key,
storage: localStorage, // 存储方式,使用localStorage,也可以使用sessionStorage
paths
};
};
export default persistedstateConfig;
/**
* https://prazdevs.github.io/pinia-plugin-persistedstate/zh/guide/config.html
* @description: 持久化配置
* @param {string} key 存储的key
* @param {Array<string>} paths 需要持久化的字段
* @return {*}
*/
const persistedstateConfig = (key: string, paths?: Array<string>) => {
return {
key,
storage: localStorage, // 存储方式,使用localStorage,也可以使用sessionStorage
paths
};
};
export default persistedstateConfig;
+12 -12
View File
@@ -1,12 +1,12 @@
// https://pinia.vuejs.org/zh/
// https://prazdevs.github.io/pinia-plugin-persistedstate/zh/
// store/index.js
import { createPinia } from "pinia";
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";
// 创建
const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
// 导出
export default pinia;
// https://pinia.vuejs.org/zh/
// https://prazdevs.github.io/pinia-plugin-persistedstate/zh/
// store/index.js
import { createPinia } from "pinia";
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";
// 创建
const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
// 导出
export default pinia;
+173 -173
View File
@@ -1,173 +1,173 @@
import { defineStore } from "pinia";
import router from "@/router/index";
import { staticRoutes } from "@/router/route";
import { getRoutersAPI } from "@/api/modules/system/index";
import { moduleReplacement, linearArray } from "@/router/route-output";
import { getUrlWithParams } from "@/utils/index";
/**
* 路由列表
* @method setTabsTitle 设置tabs标签页名称
* @methods setRoutePaths 设置路由名称集合
* @methods setTabs 添加tabs标签页
* @methods setCurrentRoute 设置系统内的当前路由
* @methods removeTabsList 删除tabs页的指定路由
* @methods removeRouteName 删除缓存路由名,用于取消页面缓存,单个删除
* @methods removeRoutePaths 删除缓存路由名,用于取消页面缓存,批量删除
* @methods resetRoute 重置动态添加的路由
* @methods initSetRouter 路由初始化
*/
export const routeConfigStore = () => {
const routeTree = ref<any>([]); // 有访问权限的路由树
const routeList = ref<any>([]); // 有访问权限的一维路由数组
const cacheRoutes = ref<string[]>([]); // 所有可缓存路由的路由路径
const tabsList = ref<Menu.MenuOptions[]>([]); // 标签页数据
const currentRoute = ref<Menu.MenuOptions | object>({}); // 当前路由
/**
* 设置tabs名称
* @param {string} title 路由名称
*/
function setTabsTitle(title: string) {
for (let i = 0; i < tabsList.value.length; i++) {
if (tabsList.value[i].path == getUrlWithParams()) {
tabsList.value[i].meta.title = title;
break;
}
}
}
/**
* 设置可缓存路由的路径 -> fullPath
* 同路由不同参兼容,会开启多个标签页,fullPath可做标识
* @param {string} path 路由fullPath
*/
function setRoutePaths(path: string) {
let state = cacheRoutes.value.some((item: string) => item === path);
if (state) return;
cacheRoutes.value.push(path);
}
/**
* 添加tabs标签页
* @param {object} route 当前tabs路由
*/
function setTabs(route: Menu.MenuOptions) {
// 顶层手动添加的全屏静态路由不参与tabs
if (staticRoutes.some(item => item.name == route.name)) return;
// 不在可访问的路由中则不参与tabs
if (!routeList.value.some((item: any) => item.name == route.name)) return;
// 当前路由在tags中是否存在
let index = tabsList.value.findIndex((item: Menu.MenuOptions) => item.path === route.path);
// 不存在,直接缓存
if (index == -1) return tabsList.value.push(route);
}
/**
* 设置系统内的当前路由数据
* @param {object} data 当前路由
*/
function setCurrentRoute(data: Menu.MenuOptions) {
// 名称一样不代表参数相同,这不用做已存在匹配,直接存储当前路由
currentRoute.value = data;
}
/**
* 删除tabs页的指定路由
* @param {string} path 路由fullPath
*/
function removeTabsList(path: string) {
const index = tabsList.value.findIndex((item: Menu.MenuOptions) => item.path === path);
if (tabsList.value[index].meta.affix) return;
if (index === -1) return;
tabsList.value.splice(index, 1);
}
/**
* 删除缓存路由,用于取消页面缓存,单个删除
* @param {string} path 路由
*/
function removeRouteName(path: string) {
const index = cacheRoutes.value.findIndex((item: string) => item === path);
if (index === -1) return;
cacheRoutes.value.splice(index, 1);
}
/**
* 删除缓存路由,用于取消页面缓存,批量删除
* @param {Array} list 路由
*/
function removeRoutePaths(list: Array<string>) {
cacheRoutes.value = cacheRoutes.value.filter((item: string) => !list.includes(item));
}
/**
* 重置动态添加的路由
*/
async function resetRoute() {
// 清除标签页数据
tabsList.value = [];
// 清除有访问权限的路由树
routeTree.value = [];
// 清除所有可缓存路由的路由路径
cacheRoutes.value = [];
// 清除当前路由
currentRoute.value = {};
// 清除动态添加的路由
routeList.value.forEach((item: any) => {
if (router.hasRoute(item.name)) router.removeRoute(item.name);
});
// 清除有访问权限的一维路由数组
routeList.value = [];
}
/**
* 路由初始化
* 1、获取过滤角色权限后排过序的的路由树,后端处理
* 2、获取路由树转换的一维路由
* 3、将模块设置为真实模块
* 4、动态添加路由
* 5、存储路由树,用于生成菜单
* 6、缓存一维路由
*/
async function initSetRouter() {
// 1、获取过滤角色权限后的树,后端做排序处理
let { data } = await getRoutersAPI();
// 验证数据有效性
if (!data || !Array.isArray(data) || data.length === 0) {
return;
}
// 2、获取路由树转换的一维路由
let flatRoute = linearArray(data);
// 3、将模块设置为真实模块
let realTree = await moduleReplacement(flatRoute);
// 4、动态添加路由
realTree.forEach((route: any) => {
if (route.meta.isFull) {
router.addRoute(route);
} else {
router.addRoute("layout", route);
}
});
// 5、存储路由树,用于生成菜单
routeTree.value = data;
// 6、缓存一维路由
routeList.value = flatRoute;
}
return {
routeTree,
routeList,
cacheRoutes,
tabsList,
currentRoute,
setTabsTitle,
setRoutePaths,
setTabs,
setCurrentRoute,
removeTabsList,
removeRouteName,
removeRoutePaths,
resetRoute,
initSetRouter
};
};
export const useRouteConfigStore = defineStore("route-config", routeConfigStore);
import { defineStore } from "pinia";
import router from "@/router/index";
import { staticRoutes } from "@/router/route";
import { getRoutersAPI } from "@/api/modules/system/index";
import { moduleReplacement, linearArray } from "@/router/route-output";
import { getUrlWithParams } from "@/utils/index";
/**
* 路由列表
* @method setTabsTitle 设置tabs标签页名称
* @methods setRoutePaths 设置路由名称集合
* @methods setTabs 添加tabs标签页
* @methods setCurrentRoute 设置系统内的当前路由
* @methods removeTabsList 删除tabs页的指定路由
* @methods removeRouteName 删除缓存路由名,用于取消页面缓存,单个删除
* @methods removeRoutePaths 删除缓存路由名,用于取消页面缓存,批量删除
* @methods resetRoute 重置动态添加的路由
* @methods initSetRouter 路由初始化
*/
export const routeConfigStore = () => {
const routeTree = ref<any>([]); // 有访问权限的路由树
const routeList = ref<any>([]); // 有访问权限的一维路由数组
const cacheRoutes = ref<string[]>([]); // 所有可缓存路由的路由路径
const tabsList = ref<Menu.MenuOptions[]>([]); // 标签页数据
const currentRoute = ref<Menu.MenuOptions | object>({}); // 当前路由
/**
* 设置tabs名称
* @param {string} title 路由名称
*/
function setTabsTitle(title: string) {
for (let i = 0; i < tabsList.value.length; i++) {
if (tabsList.value[i].path == getUrlWithParams()) {
tabsList.value[i].meta.title = title;
break;
}
}
}
/**
* 设置可缓存路由的路径 -> fullPath
* 同路由不同参兼容,会开启多个标签页,fullPath可做标识
* @param {string} path 路由fullPath
*/
function setRoutePaths(path: string) {
let state = cacheRoutes.value.some((item: string) => item === path);
if (state) return;
cacheRoutes.value.push(path);
}
/**
* 添加tabs标签页
* @param {object} route 当前tabs路由
*/
function setTabs(route: Menu.MenuOptions) {
// 顶层手动添加的全屏静态路由不参与tabs
if (staticRoutes.some(item => item.name == route.name)) return;
// 不在可访问的路由中则不参与tabs
if (!routeList.value.some((item: any) => item.name == route.name)) return;
// 当前路由在tags中是否存在
let index = tabsList.value.findIndex((item: Menu.MenuOptions) => item.path === route.path);
// 不存在,直接缓存
if (index == -1) return tabsList.value.push(route);
}
/**
* 设置系统内的当前路由数据
* @param {object} data 当前路由
*/
function setCurrentRoute(data: Menu.MenuOptions) {
// 名称一样不代表参数相同,这不用做已存在匹配,直接存储当前路由
currentRoute.value = data;
}
/**
* 删除tabs页的指定路由
* @param {string} path 路由fullPath
*/
function removeTabsList(path: string) {
const index = tabsList.value.findIndex((item: Menu.MenuOptions) => item.path === path);
if (tabsList.value[index].meta.affix) return;
if (index === -1) return;
tabsList.value.splice(index, 1);
}
/**
* 删除缓存路由,用于取消页面缓存,单个删除
* @param {string} path 路由
*/
function removeRouteName(path: string) {
const index = cacheRoutes.value.findIndex((item: string) => item === path);
if (index === -1) return;
cacheRoutes.value.splice(index, 1);
}
/**
* 删除缓存路由,用于取消页面缓存,批量删除
* @param {Array} list 路由
*/
function removeRoutePaths(list: Array<string>) {
cacheRoutes.value = cacheRoutes.value.filter((item: string) => !list.includes(item));
}
/**
* 重置动态添加的路由
*/
async function resetRoute() {
// 清除标签页数据
tabsList.value = [];
// 清除有访问权限的路由树
routeTree.value = [];
// 清除所有可缓存路由的路由路径
cacheRoutes.value = [];
// 清除当前路由
currentRoute.value = {};
// 清除动态添加的路由
routeList.value.forEach((item: any) => {
if (router.hasRoute(item.name)) router.removeRoute(item.name);
});
// 清除有访问权限的一维路由数组
routeList.value = [];
}
/**
* 路由初始化
* 1、获取过滤角色权限后排过序的的路由树,后端处理
* 2、获取路由树转换的一维路由
* 3、将模块设置为真实模块
* 4、动态添加路由
* 5、存储路由树,用于生成菜单
* 6、缓存一维路由
*/
async function initSetRouter() {
// 1、获取过滤角色权限后的树,后端做排序处理
let { data } = await getRoutersAPI();
// 验证数据有效性
if (!data || !Array.isArray(data) || data.length === 0) {
return;
}
// 2、获取路由树转换的一维路由
let flatRoute = linearArray(data);
// 3、将模块设置为真实模块
let realTree = await moduleReplacement(flatRoute);
// 4、动态添加路由
realTree.forEach((route: any) => {
if (route.meta.isFull) {
router.addRoute(route);
} else {
router.addRoute("layout", route);
}
});
// 5、存储路由树,用于生成菜单
routeTree.value = data;
// 6、缓存一维路由
routeList.value = flatRoute;
}
return {
routeTree,
routeList,
cacheRoutes,
tabsList,
currentRoute,
setTabsTitle,
setRoutePaths,
setTabs,
setCurrentRoute,
removeTabsList,
removeRouteName,
removeRoutePaths,
resetRoute,
initSetRouter
};
};
export const useRouteConfigStore = defineStore("route-config", routeConfigStore);
+113 -113
View File
@@ -1,113 +1,113 @@
import { defineStore } from "pinia";
import persistedstateConfig from "@/store/config/index";
/**
* 全局配置
* @methods setCollapsed 设置菜单折叠
* @methods setRefreshPage 刷新页面
* @methods setLanguage 设置语言
*/
const themeConfig = () => {
// 是否折叠菜单
const collapsed = ref<boolean>(false);
// 刷新页面
const refreshPage = ref<boolean>(true);
// 系统语言
const language = ref<string>("zh-CN");
// 黑暗模式
const darkMode = ref<boolean>(false);
// 菜单手风琴
const isAccordion = ref<boolean>(true);
// 面包屑渲染
const isBreadcrumb = ref<boolean>(true);
// 标签栏渲染
const isTabs = ref<boolean>(true);
// 页脚渲染
const isFooter = ref<boolean>(true);
// 水印
const watermark = ref<string>("");
// 水印风格
const watermarkStyle = ref<{ fontSize: number; color: string }>({
fontSize: 12,
color: "rgba(0, 0, 0, 0.15)"
});
// 水印角度
const watermarkRotate = ref<number>(330);
// 水印间隙
const watermarkGap = ref<[number, number]>([100, 100]);
// 防止调试
const debugPrevention = ref<boolean>(false);
// 布局模式:layoutDefaults、layoutHead、layoutMixing
const layoutType = ref<string>("layoutDefaults");
// 色弱模式
const colorWeakMode = ref<boolean>(false);
// 灰色模式
const grayMode = ref<boolean>(false);
// 侧边栏深色
const asideDark = ref<boolean>(false);
// 页面过渡方式
const transitionPage = ref<string>("fadeInOut");
// 主题色
const themeColor = ref<string>("#165DFF");
// 调色盘
const presetColors = ref<string[]>([
"#165DFF",
"#F53F3F",
"#F77234",
"#FF7D00",
"#F7BA1E",
"#FADC19",
"#9FDB1D",
"#00B42A",
"#3491FA",
"#c34d9c",
"#722ED1",
"#E6A23C",
"#F56C6C",
"#409EFF",
"#42b883",
"#b1d391"
]);
// 折叠菜单
function setCollapsed(data: boolean) {
collapsed.value = data;
}
// 刷新页面
function setRefreshPage(data: boolean) {
refreshPage.value = data;
}
// 设置语言
function setLanguage(data: string) {
language.value = data;
}
return {
collapsed,
refreshPage,
language,
darkMode,
isAccordion,
isBreadcrumb,
isTabs,
isFooter,
watermark,
watermarkStyle,
watermarkRotate,
watermarkGap,
debugPrevention,
layoutType,
colorWeakMode,
grayMode,
asideDark,
transitionPage,
themeColor,
presetColors,
setCollapsed,
setRefreshPage,
setLanguage
};
};
export const useThemeConfig = defineStore("theme-config", themeConfig, {
persist: persistedstateConfig("theme-config")
});
import { defineStore } from "pinia";
import persistedstateConfig from "@/store/config/index";
/**
* 全局配置
* @methods setCollapsed 设置菜单折叠
* @methods setRefreshPage 刷新页面
* @methods setLanguage 设置语言
*/
const themeConfig = () => {
// 是否折叠菜单
const collapsed = ref<boolean>(false);
// 刷新页面
const refreshPage = ref<boolean>(true);
// 系统语言
const language = ref<string>("zh-CN");
// 黑暗模式
const darkMode = ref<boolean>(false);
// 菜单手风琴
const isAccordion = ref<boolean>(true);
// 面包屑渲染
const isBreadcrumb = ref<boolean>(true);
// 标签栏渲染
const isTabs = ref<boolean>(true);
// 页脚渲染
const isFooter = ref<boolean>(true);
// 水印
const watermark = ref<string>("");
// 水印风格
const watermarkStyle = ref<{ fontSize: number; color: string }>({
fontSize: 12,
color: "rgba(0, 0, 0, 0.15)"
});
// 水印角度
const watermarkRotate = ref<number>(330);
// 水印间隙
const watermarkGap = ref<[number, number]>([100, 100]);
// 防止调试
const debugPrevention = ref<boolean>(false);
// 布局模式:layoutDefaults、layoutHead、layoutMixing
const layoutType = ref<string>("layoutDefaults");
// 色弱模式
const colorWeakMode = ref<boolean>(false);
// 灰色模式
const grayMode = ref<boolean>(false);
// 侧边栏深色
const asideDark = ref<boolean>(false);
// 页面过渡方式
const transitionPage = ref<string>("fadeInOut");
// 主题色
const themeColor = ref<string>("#165DFF");
// 调色盘
const presetColors = ref<string[]>([
"#165DFF",
"#F53F3F",
"#F77234",
"#FF7D00",
"#F7BA1E",
"#FADC19",
"#9FDB1D",
"#00B42A",
"#3491FA",
"#c34d9c",
"#722ED1",
"#E6A23C",
"#F56C6C",
"#409EFF",
"#42b883",
"#b1d391"
]);
// 折叠菜单
function setCollapsed(data: boolean) {
collapsed.value = data;
}
// 刷新页面
function setRefreshPage(data: boolean) {
refreshPage.value = data;
}
// 设置语言
function setLanguage(data: string) {
language.value = data;
}
return {
collapsed,
refreshPage,
language,
darkMode,
isAccordion,
isBreadcrumb,
isTabs,
isFooter,
watermark,
watermarkStyle,
watermarkRotate,
watermarkGap,
debugPrevention,
layoutType,
colorWeakMode,
grayMode,
asideDark,
transitionPage,
themeColor,
presetColors,
setCollapsed,
setRefreshPage,
setLanguage
};
};
export const useThemeConfig = defineStore("theme-config", themeConfig, {
persist: persistedstateConfig("theme-config")
});
+64 -64
View File
@@ -1,64 +1,64 @@
import { defineStore } from "pinia";
import persistedstateConfig from "@/store/config/index";
import { getUserInfoAPI } from "@/api/modules/user/index";
interface Account {
user: any; // 用户信息
roles: string[]; // 角色
permissions: string[]; // 权限
}
/**
* 用户信息
* @methods setAccount 设置账号信息
* @methods setToken 设置token
* @methods logOut 退出登录
*/
const userInfoStore = () => {
// 账号信息
const account = ref<Account>({
user: {}, // 用户信息
roles: [], // 角色
permissions: [] // 权限
});
const trade_type = ref<Record<string, string>>({});
const trade_fiat = ref<string[]>([]);
const trade_crypto = ref<string[]>([]);
const admin_username = ref<string>("");
async function setAccount() {
let data = await getUserInfoAPI();
// 确保返回的数据有效
if (data && data.data) {
trade_type.value = data.data.trade_type || {};
trade_fiat.value = data.data.trade_fiat || [];
trade_crypto.value = data.data.trade_crypto || [];
admin_username.value = data.data.admin_username || "";
}
}
// 设置token
const token = ref<string>("");
async function setToken(data: string) {
token.value = data;
}
// 退出登录
async function logOut() {
// 清除账号数据
account.value = {
user: {},
roles: [],
permissions: []
};
token.value = "";
}
return { account, token, setAccount, setToken, logOut, trade_type, trade_fiat, trade_crypto, admin_username };
};
export const useUserInfoStore = defineStore("user-info", userInfoStore, {
persist: persistedstateConfig("user-info", ["token", "account", "trade_type", "trade_fiat", "trade_crypto", "admin_username"])
});
import { defineStore } from "pinia";
import persistedstateConfig from "@/store/config/index";
import { getUserInfoAPI } from "@/api/modules/user/index";
interface Account {
user: any; // 用户信息
roles: string[]; // 角色
permissions: string[]; // 权限
}
/**
* 用户信息
* @methods setAccount 设置账号信息
* @methods setToken 设置token
* @methods logOut 退出登录
*/
const userInfoStore = () => {
// 账号信息
const account = ref<Account>({
user: {}, // 用户信息
roles: [], // 角色
permissions: [] // 权限
});
const trade_type = ref<Record<string, string>>({});
const trade_fiat = ref<string[]>([]);
const trade_crypto = ref<string[]>([]);
const admin_username = ref<string>("");
async function setAccount() {
let data = await getUserInfoAPI();
// 确保返回的数据有效
if (data && data.data) {
trade_type.value = data.data.trade_type || {};
trade_fiat.value = data.data.trade_fiat || [];
trade_crypto.value = data.data.trade_crypto || [];
admin_username.value = data.data.admin_username || "";
}
}
// 设置token
const token = ref<string>("");
async function setToken(data: string) {
token.value = data;
}
// 退出登录
async function logOut() {
// 清除账号数据
account.value = {
user: {},
roles: [],
permissions: []
};
token.value = "";
}
return { account, token, setAccount, setToken, logOut, trade_type, trade_fiat, trade_crypto, admin_username };
};
export const useUserInfoStore = defineStore("user-info", userInfoStore, {
persist: persistedstateConfig("user-info", ["token", "account", "trade_type", "trade_fiat", "trade_crypto", "admin_username"])
});
+32 -32
View File
@@ -1,32 +1,32 @@
@use "@/style/var/index" as *;
@use "@/style/model";
@use "@/style/media";
* {
padding: 0;
margin: 0;
}
html,
body,
#app {
padding: 0;
margin: 0;
overflow: hidden;
}
html {
font-size: 14px;
}
#app {
overflow: hidden;
}
// 设置全局颜色-关联黑暗模式
// 全局取一级容器背景色$color-bg-2,main窗口取边框色浅色$color-border-1
body {
color: $color-text-1; // 整体文字的颜色
background: $color-bg-2; // body背景颜色
}
// 设置nprogress进度条样式
#nprogress .bar {
background: $color-primary !important;
}
@use "@/style/var/index" as *;
@use "@/style/model";
@use "@/style/media";
* {
padding: 0;
margin: 0;
}
html,
body,
#app {
padding: 0;
margin: 0;
overflow: hidden;
}
html {
font-size: 14px;
}
#app {
overflow: hidden;
}
// 设置全局颜色-关联黑暗模式
// 全局取一级容器背景色$color-bg-2,main窗口取边框色浅色$color-border-1
body {
color: $color-text-1; // 整体文字的颜色
background: $color-bg-2; // body背景颜色
}
// 设置nprogress进度条样式
#nprogress .bar {
background: $color-primary !important;
}
+1 -1
View File
@@ -1 +1 @@
@use "@/style/media/layout";
@use "@/style/media/layout";
+45 -45
View File
@@ -1,45 +1,45 @@
@use "@/style/var/index" as *;
// 处理首页数据图大小
// 页面宽度 大于 0px 小于 992px;
@media screen and (min-width: $xs) and (max-width: $lg) {
.sell-histogram {
width: 100%;
height: 400px;
padding-bottom: $padding;
}
.daily-analysis {
width: 100%;
height: 400px;
padding-bottom: $padding;
}
}
// 页面宽度 大于 992px 小于 1600px;
@media screen and (min-width: $lg) and (max-width: $xxl) {
.sell-histogram {
width: 100%;
height: 400px;
padding-bottom: $padding;
}
.daily-analysis {
width: 100%;
height: 400px;
padding-bottom: $padding;
}
}
// 页面宽度 大于 1600px;
@media screen and (min-width: $xxl) {
.sell-histogram {
width: calc(100% - 600px - $padding);
height: 400px;
padding-bottom: $padding;
}
.daily-analysis {
width: 600px;
height: 400px;
padding-bottom: $padding;
margin-left: $padding;
}
}
@use "@/style/var/index" as *;
// 处理首页数据图大小
// 页面宽度 大于 0px 小于 992px;
@media screen and (min-width: $xs) and (max-width: $lg) {
.sell-histogram {
width: 100%;
height: 400px;
padding-bottom: $padding;
}
.daily-analysis {
width: 100%;
height: 400px;
padding-bottom: $padding;
}
}
// 页面宽度 大于 992px 小于 1600px;
@media screen and (min-width: $lg) and (max-width: $xxl) {
.sell-histogram {
width: 100%;
height: 400px;
padding-bottom: $padding;
}
.daily-analysis {
width: 100%;
height: 400px;
padding-bottom: $padding;
}
}
// 页面宽度 大于 1600px;
@media screen and (min-width: $xxl) {
.sell-histogram {
width: calc(100% - 600px - $padding);
height: 400px;
padding-bottom: $padding;
}
.daily-analysis {
width: 600px;
height: 400px;
padding-bottom: $padding;
margin-left: $padding;
}
}
+7 -7
View File
@@ -1,7 +1,7 @@
/* ArcoDesign命名空间 */
declare namespace ArcoDesign {
interface ArcoSubmit {
values: Record<string, any>;
errors: Record<string, any> | undefined;
}
}
/* ArcoDesign命名空间 */
declare namespace ArcoDesign {
interface ArcoSubmit {
values: Record<string, any>;
errors: Record<string, any> | undefined;
}
}
+50 -50
View File
@@ -1,50 +1,50 @@
/* ts命名空间 */
/* 路由-Menu */
declare namespace Menu {
interface MenuOptions {
id: string;
parentId: string;
fullPath?: stirng;
path: string;
name: string;
redirect?: string;
component?: string | (() => Promise<unknown>);
meta: MetaType;
children?: MenuOptions[] | null | any;
}
interface MetaType {
title: string;
hide: boolean;
disable: boolean;
keepAlive: boolean;
affix: boolean;
link?: string;
iframe?: boolean;
roles: Array<string>;
icon?: string;
svgIcon?: string;
sort?: number;
type?: number;
}
}
/* tabs菜单 */
declare namespace TabsMenu {
interface list {
list: Array<{ type: number; icon: string; title: string }>;
}
interface menu {
type: number;
icon: string;
title: string;
}
}
/* viteEnv */
interface ViteEnv {
VITE_GLOB_APP_TITLE: string;
VITE_IMG_BASE_URL: string;
VITE_APP_OPEN_MOCK: boolean | string;
VITE_USER_NODE_ENV: "development" | "production" | "test";
VITE_PUBLIC_PATH: string;
VITE_APP_BASE_URL: string;
}
/* ts命名空间 */
/* 路由-Menu */
declare namespace Menu {
interface MenuOptions {
id: string;
parentId: string;
fullPath?: stirng;
path: string;
name: string;
redirect?: string;
component?: string | (() => Promise<unknown>);
meta: MetaType;
children?: MenuOptions[] | null | any;
}
interface MetaType {
title: string;
hide: boolean;
disable: boolean;
keepAlive: boolean;
affix: boolean;
link?: string;
iframe?: boolean;
roles: Array<string>;
icon?: string;
svgIcon?: string;
sort?: number;
type?: number;
}
}
/* tabs菜单 */
declare namespace TabsMenu {
interface list {
list: Array<{ type: number; icon: string; title: string }>;
}
interface menu {
type: number;
icon: string;
title: string;
}
}
/* viteEnv */
interface ViteEnv {
VITE_GLOB_APP_TITLE: string;
VITE_IMG_BASE_URL: string;
VITE_APP_OPEN_MOCK: boolean | string;
VITE_USER_NODE_ENV: "development" | "production" | "test";
VITE_PUBLIC_PATH: string;
VITE_APP_BASE_URL: string;
}
+195 -195
View File
@@ -1,195 +1,195 @@
/**
* 深拷贝
* @param { string } data 需要深拷贝的数据
* @returns 深拷贝的数据
*/
export function deepClone(data: any) {
let stack = [];
let cloned;
if (Array.isArray(data)) {
cloned = [];
} else if (typeof data === "object" && data !== null) {
cloned = {};
} else {
return data;
}
stack.push({
original: data,
copy: cloned
});
while (stack.length > 0) {
let current: any = stack.pop();
let original = current.original;
let copy = current.copy;
for (let key in original) {
if (original.hasOwnProperty(key)) {
let value = original[key];
if (typeof value === "object" && value !== null) {
copy[key] = Array.isArray(value) ? [] : {};
stack.push({
original: value,
copy: copy[key]
});
} else {
copy[key] = value;
}
}
}
}
return cloned;
}
/**
* 获取浏览器默认语言
* @returns 语言类型
*/
export const webDefaultLanguage = () => navigator.language;
/**
* 时间戳转 年月日时分秒
* 若timestamp不传则取当前时间
* 若type不传则取 年月日时分秒
* @param { number } timestamp 时间戳
* @return 返回年月日时分秒字符串
*/
export const getTimestamp = (timestamp: string | number | null, type: string) => {
let date = null;
if (timestamp) {
date = new Date(timestamp);
} else {
date = new Date();
}
let Year = String(date.getFullYear());
let Moth = String(date.getMonth() + 1).padStart(2, "0");
let Day = String(date.getDate()).padStart(2, "0");
let Hour = String(date.getHours()).padStart(2, "0");
let Minute = String(date.getMinutes()).padStart(2, "0");
let Seconds = String(date.getSeconds()).padStart(2, "0");
if (type === "yyyy") {
return `${Year}`;
}
if (type === "yyyy-MM") {
return `${Year}-${Moth}`;
}
if (type === "yyyy-MM-dd") {
return `${Year}-${Moth}-${Day}`;
}
return `${Year}-${Moth}-${Day} ${Hour}:${Minute}:${Seconds}`;
};
/**
* 根据当前日期前推指定日期
* @param { number } days 需要前推的天数
* @return {Array[]} 是否为空对象 [前推天数的日期,当前日期]
*/
export const getDatesForwardDate = (days = 0) => {
const today = new Date();
const firstDay: any = new Date(today);
firstDay.setDate(firstDay.getDate() - days); // 向前推指定天,得到前指定天数的第一天
const lastDay: any = new Date(today);
lastDay.setDate(lastDay.getDate() - 1); // 昨天是前指定天数的最后一天
const firstDayFormatted = getTimestamp(firstDay, "YYYY-MM-DD");
const lastDayFormatted = getTimestamp(lastDay, "YYYY-MM-DD");
return [firstDayFormatted, lastDayFormatted];
};
/**
* 给formData循环添加参数,过滤null、undefined、空字符串、NaN
* 示例:let data = appendFormData(your-object);
* @param { object } obj 参数对象
* @return 返回formData对象
*/
export const appendFormData = (obj: any) => {
let formData = new FormData();
function deepAppendFormData(formData: any, data: any, parentKey = "") {
if (Array.isArray(data) || (typeof data === "object" && data !== null)) {
// 如果数据是数组或对象,序列化为 JSON 字符串
formData.append(parentKey, JSON.stringify(data));
} else if (data !== null && data !== undefined && !Number.isNaN(data) && data !== "") {
// 如果数据是基本类型,直接添加
formData.append(parentKey, data);
}
}
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
deepAppendFormData(formData, obj[key], key);
}
}
deepAppendFormData(formData, obj);
return formData;
};
/**
* 判断是否为空对象
* @param {object} obj 对象
* @returns {boolean} 是否为空对象
*/
export const isEmptyObject = (obj: object) => {
// 校验是否为对象且不为 null
if (typeof obj !== "object" || obj === null) {
return false;
}
return Object.keys(obj).length === 0 && obj.constructor === Object;
};
/**
* 判断是否为安全环境https或localhost
* @returns 是否为安全环境https或localhost
*/
export const isSecureEnvironment = () => {
const { protocol, hostname } = window.location;
// 检查协议是否为HTTPS
const isHttps = protocol === "https:";
// 检查主机名是否为localhost或本地IP(支持IPv4和IPv6)
const isLocalhost =
hostname === "localhost" || hostname === "127.0.0.1" || hostname === "0.0.0.0" || hostname === "[::1]" || hostname === "::1";
return isHttps || isLocalhost;
};
/**
* 获取不同路由模式所对应的 url + params
* @returns {String} 返回路径
*/
export const getUrlWithParams = () => {
type UrlParams = {
hash: string;
history: string;
};
if (typeof window === "undefined") return "";
const url: UrlParams = {
hash: window.location.hash.substring(1),
history: window.location.pathname + window.location.search
};
const mode = (import.meta.env.VITE_ROUTER_MODE as keyof UrlParams) || "history";
return url[mode] || "";
};
/**
* 下划线转驼峰
* @param v 下划线字符串
* @returns 驼峰字符串
*/
export const getPascalCase = (v: string) => {
// 处理空字符串情况
if (!v) return v;
// 1. 替换所有下划线序列及其后的首个字符
// - 正则 /_+(.)/g 匹配一个或多个下划线后紧跟的任意字符
// - 替换函数将匹配的字符转为大写(字母则大写,非字母则原样保留)
let result = v.replace(/_+(.)/g, (_, char) => char.toUpperCase());
// 2. 删除开头和结尾剩余的下划线
result = result.replace(/^_+|_+$/g, "");
// 3. 将首字母转为大写后返回
return result.charAt(0).toUpperCase() + result.slice(1);
};
/**
* 深拷贝
* @param { string } data 需要深拷贝的数据
* @returns 深拷贝的数据
*/
export function deepClone(data: any) {
let stack = [];
let cloned;
if (Array.isArray(data)) {
cloned = [];
} else if (typeof data === "object" && data !== null) {
cloned = {};
} else {
return data;
}
stack.push({
original: data,
copy: cloned
});
while (stack.length > 0) {
let current: any = stack.pop();
let original = current.original;
let copy = current.copy;
for (let key in original) {
if (original.hasOwnProperty(key)) {
let value = original[key];
if (typeof value === "object" && value !== null) {
copy[key] = Array.isArray(value) ? [] : {};
stack.push({
original: value,
copy: copy[key]
});
} else {
copy[key] = value;
}
}
}
}
return cloned;
}
/**
* 获取浏览器默认语言
* @returns 语言类型
*/
export const webDefaultLanguage = () => navigator.language;
/**
* 时间戳转 年月日时分秒
* 若timestamp不传则取当前时间
* 若type不传则取 年月日时分秒
* @param { number } timestamp 时间戳
* @return 返回年月日时分秒字符串
*/
export const getTimestamp = (timestamp: string | number | null, type: string) => {
let date = null;
if (timestamp) {
date = new Date(timestamp);
} else {
date = new Date();
}
let Year = String(date.getFullYear());
let Moth = String(date.getMonth() + 1).padStart(2, "0");
let Day = String(date.getDate()).padStart(2, "0");
let Hour = String(date.getHours()).padStart(2, "0");
let Minute = String(date.getMinutes()).padStart(2, "0");
let Seconds = String(date.getSeconds()).padStart(2, "0");
if (type === "yyyy") {
return `${Year}`;
}
if (type === "yyyy-MM") {
return `${Year}-${Moth}`;
}
if (type === "yyyy-MM-dd") {
return `${Year}-${Moth}-${Day}`;
}
return `${Year}-${Moth}-${Day} ${Hour}:${Minute}:${Seconds}`;
};
/**
* 根据当前日期前推指定日期
* @param { number } days 需要前推的天数
* @return {Array[]} 是否为空对象 [前推天数的日期,当前日期]
*/
export const getDatesForwardDate = (days = 0) => {
const today = new Date();
const firstDay: any = new Date(today);
firstDay.setDate(firstDay.getDate() - days); // 向前推指定天,得到前指定天数的第一天
const lastDay: any = new Date(today);
lastDay.setDate(lastDay.getDate() - 1); // 昨天是前指定天数的最后一天
const firstDayFormatted = getTimestamp(firstDay, "YYYY-MM-DD");
const lastDayFormatted = getTimestamp(lastDay, "YYYY-MM-DD");
return [firstDayFormatted, lastDayFormatted];
};
/**
* 给formData循环添加参数,过滤null、undefined、空字符串、NaN
* 示例:let data = appendFormData(your-object);
* @param { object } obj 参数对象
* @return 返回formData对象
*/
export const appendFormData = (obj: any) => {
let formData = new FormData();
function deepAppendFormData(formData: any, data: any, parentKey = "") {
if (Array.isArray(data) || (typeof data === "object" && data !== null)) {
// 如果数据是数组或对象,序列化为 JSON 字符串
formData.append(parentKey, JSON.stringify(data));
} else if (data !== null && data !== undefined && !Number.isNaN(data) && data !== "") {
// 如果数据是基本类型,直接添加
formData.append(parentKey, data);
}
}
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
deepAppendFormData(formData, obj[key], key);
}
}
deepAppendFormData(formData, obj);
return formData;
};
/**
* 判断是否为空对象
* @param {object} obj 对象
* @returns {boolean} 是否为空对象
*/
export const isEmptyObject = (obj: object) => {
// 校验是否为对象且不为 null
if (typeof obj !== "object" || obj === null) {
return false;
}
return Object.keys(obj).length === 0 && obj.constructor === Object;
};
/**
* 判断是否为安全环境https或localhost
* @returns 是否为安全环境https或localhost
*/
export const isSecureEnvironment = () => {
const { protocol, hostname } = window.location;
// 检查协议是否为HTTPS
const isHttps = protocol === "https:";
// 检查主机名是否为localhost或本地IP(支持IPv4和IPv6)
const isLocalhost =
hostname === "localhost" || hostname === "127.0.0.1" || hostname === "0.0.0.0" || hostname === "[::1]" || hostname === "::1";
return isHttps || isLocalhost;
};
/**
* 获取不同路由模式所对应的 url + params
* @returns {String} 返回路径
*/
export const getUrlWithParams = () => {
type UrlParams = {
hash: string;
history: string;
};
if (typeof window === "undefined") return "";
const url: UrlParams = {
hash: window.location.hash.substring(1),
history: window.location.pathname + window.location.search
};
const mode = (import.meta.env.VITE_ROUTER_MODE as keyof UrlParams) || "history";
return url[mode] || "";
};
/**
* 下划线转驼峰
* @param v 下划线字符串
* @returns 驼峰字符串
*/
export const getPascalCase = (v: string) => {
// 处理空字符串情况
if (!v) return v;
// 1. 替换所有下划线序列及其后的首个字符
// - 正则 /_+(.)/g 匹配一个或多个下划线后紧跟的任意字符
// - 替换函数将匹配的字符转为大写(字母则大写,非字母则原样保留)
let result = v.replace(/_+(.)/g, (_, char) => char.toUpperCase());
// 2. 删除开头和结尾剩余的下划线
result = result.replace(/^_+|_+$/g, "");
// 3. 将首字母转为大写后返回
return result.charAt(0).toUpperCase() + result.slice(1);
};
+29 -29
View File
@@ -1,29 +1,29 @@
/**
* 全局加载 loading-page
* @method start 创建 loading
* @method done 移除 loading
*/
export const loadingPage = {
// 开始渲染loading
start: () => {
// 获取顶层body
// 将新创建的dc-loader元素(div)插入到body元素的子元素列表中的指定位置(在指定元素之前)
// 插入的位置是作为body元素的第一个子元素,即页面的最顶部位置
const bodyDom: Element = document.body;
const div = document.createElement("div");
div.className = "loading-page";
const loader = document.createElement("div");
loader.className = "dc-loader";
div.appendChild(loader);
bodyDom.insertBefore(div, bodyDom.firstChild);
},
// 结束渲染loading
done: (time: number = 0) => {
setTimeout(() => {
// 找到第一个匹配对象
// 找到loading-page的父节点,移除loading-page
const dom = document.querySelector(".loading-page");
dom?.parentNode?.removeChild(dom);
}, time);
}
};
/**
* 全局加载 loading-page
* @method start 创建 loading
* @method done 移除 loading
*/
export const loadingPage = {
// 开始渲染loading
start: () => {
// 获取顶层body
// 将新创建的dc-loader元素(div)插入到body元素的子元素列表中的指定位置(在指定元素之前)
// 插入的位置是作为body元素的第一个子元素,即页面的最顶部位置
const bodyDom: Element = document.body;
const div = document.createElement("div");
div.className = "loading-page";
const loader = document.createElement("div");
loader.className = "dc-loader";
div.appendChild(loader);
bodyDom.insertBefore(div, bodyDom.firstChild);
},
// 结束渲染loading
done: (time: number = 0) => {
setTimeout(() => {
// 找到第一个匹配对象
// 找到loading-page的父节点,移除loading-page
const dom = document.querySelector(".loading-page");
dom?.parentNode?.removeChild(dom);
}, time);
}
};
+15 -15
View File
@@ -1,15 +1,15 @@
/**
* px转响应式px
* 示例:$px2px(20, 1920),在1920px的设计稿上元素大小为20px,若在其它窗口大小下,会根据窗口大小自动缩放
* @param {number} px 设计稿元素大小
* @param {number} viewport 设计稿窗口大小
* @returns {number} 响应式px
*/
export const px2px = (px: number, viewport: number): number => {
const viewportWidth: number = (window.innerWidth || document.documentElement.clientWidth) as number;
let originalWidth = px;
let originalViewport = viewport;
// 计算新视口下的宽度
let newWidth = (originalWidth / originalViewport) * viewportWidth;
return parseInt(String(newWidth));
};
/**
* px转响应式px
* 示例:$px2px(20, 1920),在1920px的设计稿上元素大小为20px,若在其它窗口大小下,会根据窗口大小自动缩放
* @param {number} px 设计稿元素大小
* @param {number} viewport 设计稿窗口大小
* @returns {number} 响应式px
*/
export const px2px = (px: number, viewport: number): number => {
const viewportWidth: number = (window.innerWidth || document.documentElement.clientWidth) as number;
let originalWidth = px;
let originalViewport = viewport;
// 计算新视口下的宽度
let newWidth = (originalWidth / originalViewport) * viewportWidth;
return parseInt(String(newWidth));
};
+117 -117
View File
@@ -1,117 +1,117 @@
/**
* @description: 测试多级菜单
*/
export const testMultilevelMenu = [
{
path: "/multilevel-menu/third-menu-3",
name: "third-menu-3",
component: () => import("@/views/multilevel-menu/third-menu/third-menu-3.vue"),
meta: {
title: "third-menu-3",
link: "",
hide: false,
keepAlive: true,
affix: false,
iframe: false,
roles: ["admin"],
icon: "icon-menu",
sort: 3
}
},
{
path: "/multilevel-menu/third-menu-4",
name: "third-menu-4",
component: () => import("@/views/multilevel-menu/third-menu/third-menu-4.vue"),
meta: {
title: "third-menu-4",
link: "",
hide: false,
keepAlive: true,
affix: false,
iframe: false,
roles: ["admin"],
icon: "icon-menu",
sort: 4
}
},
{
path: "/multilevel-menu/third-menu-5",
name: "third-menu-5",
component: () => import("@/views/multilevel-menu/third-menu/third-menu-5.vue"),
meta: {
title: "third-menu-5",
link: "",
hide: false,
keepAlive: true,
affix: false,
iframe: false,
roles: ["admin"],
icon: "icon-menu",
sort: 5
}
},
{
path: "/multilevel-menu/third-menu-6",
name: "third-menu-6",
component: () => import("@/views/multilevel-menu/third-menu/third-menu-6.vue"),
meta: {
title: "third-menu-6",
link: "",
hide: false,
keepAlive: true,
affix: false,
iframe: false,
roles: ["admin"],
icon: "icon-menu",
sort: 6
}
},
{
path: "/multilevel-menu/third-menu-7",
name: "third-menu-7",
component: () => import("@/views/multilevel-menu/third-menu/third-menu-7.vue"),
meta: {
title: "third-menu-7",
link: "",
hide: false,
keepAlive: true,
affix: false,
iframe: false,
roles: ["admin"],
icon: "icon-menu",
sort: 7
}
},
{
path: "/multilevel-menu/third-menu-8",
name: "third-menu-8",
component: () => import("@/views/multilevel-menu/third-menu/third-menu-8.vue"),
meta: {
title: "third-menu-8",
link: "",
hide: false,
keepAlive: true,
affix: false,
iframe: false,
roles: ["admin"],
icon: "icon-menu",
sort: 8
}
},
{
path: "/multilevel-menu/third-menu-9",
name: "third-menu-9",
component: () => import("@/views/multilevel-menu/third-menu/third-menu-9.vue"),
meta: {
title: "third-menu-9",
link: "",
hide: false,
keepAlive: true,
affix: false,
iframe: false,
roles: ["admin"],
icon: "icon-menu",
sort: 9
}
}
];
/**
* @description: 测试多级菜单
*/
export const testMultilevelMenu = [
{
path: "/multilevel-menu/third-menu-3",
name: "third-menu-3",
component: () => import("@/views/multilevel-menu/third-menu/third-menu-3.vue"),
meta: {
title: "third-menu-3",
link: "",
hide: false,
keepAlive: true,
affix: false,
iframe: false,
roles: ["admin"],
icon: "icon-menu",
sort: 3
}
},
{
path: "/multilevel-menu/third-menu-4",
name: "third-menu-4",
component: () => import("@/views/multilevel-menu/third-menu/third-menu-4.vue"),
meta: {
title: "third-menu-4",
link: "",
hide: false,
keepAlive: true,
affix: false,
iframe: false,
roles: ["admin"],
icon: "icon-menu",
sort: 4
}
},
{
path: "/multilevel-menu/third-menu-5",
name: "third-menu-5",
component: () => import("@/views/multilevel-menu/third-menu/third-menu-5.vue"),
meta: {
title: "third-menu-5",
link: "",
hide: false,
keepAlive: true,
affix: false,
iframe: false,
roles: ["admin"],
icon: "icon-menu",
sort: 5
}
},
{
path: "/multilevel-menu/third-menu-6",
name: "third-menu-6",
component: () => import("@/views/multilevel-menu/third-menu/third-menu-6.vue"),
meta: {
title: "third-menu-6",
link: "",
hide: false,
keepAlive: true,
affix: false,
iframe: false,
roles: ["admin"],
icon: "icon-menu",
sort: 6
}
},
{
path: "/multilevel-menu/third-menu-7",
name: "third-menu-7",
component: () => import("@/views/multilevel-menu/third-menu/third-menu-7.vue"),
meta: {
title: "third-menu-7",
link: "",
hide: false,
keepAlive: true,
affix: false,
iframe: false,
roles: ["admin"],
icon: "icon-menu",
sort: 7
}
},
{
path: "/multilevel-menu/third-menu-8",
name: "third-menu-8",
component: () => import("@/views/multilevel-menu/third-menu/third-menu-8.vue"),
meta: {
title: "third-menu-8",
link: "",
hide: false,
keepAlive: true,
affix: false,
iframe: false,
roles: ["admin"],
icon: "icon-menu",
sort: 8
}
},
{
path: "/multilevel-menu/third-menu-9",
name: "third-menu-9",
component: () => import("@/views/multilevel-menu/third-menu/third-menu-9.vue"),
meta: {
title: "third-menu-9",
link: "",
hide: false,
keepAlive: true,
affix: false,
iframe: false,
roles: ["admin"],
icon: "icon-menu",
sort: 9
}
}
];
+49 -49
View File
@@ -1,49 +1,49 @@
<template>
<div class="page-404">
<div>
<s-svg-icon name="暂无权限" :size="500" />
</div>
<div class="prompt">
<div class="title">401</div>
<div class="text">抱歉,暂无访问权限~</div>
<a-button type="primary" @click="onBack">立即返回</a-button>
</div>
</div>
</template>
<script setup lang="ts">
import { useRouter } from "vue-router";
const router = useRouter();
const onBack = () => {
if (window.history.state.back !== null) {
router.replace(window.history.state.back);
} else {
router.replace("/login");
}
};
</script>
<style lang="scss" scoped>
.page-404 {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
padding: $padding;
overflow: hidden;
.prompt {
row-gap: $padding;
width: 250px;
}
.title {
font-size: 80px;
color: $color-text-1;
}
.text {
margin-bottom: $padding;
font-size: $font-size-body-3;
color: $color-text-2;
}
}
</style>
<template>
<div class="page-404">
<div>
<s-svg-icon name="暂无权限" :size="500" />
</div>
<div class="prompt">
<div class="title">401</div>
<div class="text">抱歉,暂无访问权限~</div>
<a-button type="primary" @click="onBack">立即返回</a-button>
</div>
</div>
</template>
<script setup lang="ts">
import { useRouter } from "vue-router";
const router = useRouter();
const onBack = () => {
if (window.history.state.back !== null) {
router.replace(window.history.state.back);
} else {
router.replace("/login");
}
};
</script>
<style lang="scss" scoped>
.page-404 {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
padding: $padding;
overflow: hidden;
.prompt {
row-gap: $padding;
width: 250px;
}
.title {
font-size: 80px;
color: $color-text-1;
}
.text {
margin-bottom: $padding;
font-size: $font-size-body-3;
color: $color-text-2;
}
}
</style>
+49 -49
View File
@@ -1,49 +1,49 @@
<template>
<div class="page-404">
<div>
<s-svg-icon name="内容加载失败" :size="500" />
</div>
<div class="prompt">
<div class="title">404</div>
<div class="text">抱歉,访问的页面不存在~</div>
<a-button type="primary" @click="onBack">立即返回</a-button>
</div>
</div>
</template>
<script setup lang="ts">
import { useRouter } from "vue-router";
const router = useRouter();
const onBack = () => {
if (window.history.state.back !== null) {
router.replace(window.history.state.back);
} else {
router.replace("/login");
}
};
</script>
<style lang="scss" scoped>
.page-404 {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
padding: $padding;
overflow: hidden;
.prompt {
row-gap: $padding;
width: 250px;
}
.title {
font-size: 80px;
color: $color-text-1;
}
.text {
margin-bottom: $padding;
font-size: $font-size-body-3;
color: $color-text-2;
}
}
</style>
<template>
<div class="page-404">
<div>
<s-svg-icon name="内容加载失败" :size="500" />
</div>
<div class="prompt">
<div class="title">404</div>
<div class="text">抱歉,访问的页面不存在~</div>
<a-button type="primary" @click="onBack">立即返回</a-button>
</div>
</div>
</template>
<script setup lang="ts">
import { useRouter } from "vue-router";
const router = useRouter();
const onBack = () => {
if (window.history.state.back !== null) {
router.replace(window.history.state.back);
} else {
router.replace("/login");
}
};
</script>
<style lang="scss" scoped>
.page-404 {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
padding: $padding;
overflow: hidden;
.prompt {
row-gap: $padding;
width: 250px;
}
.title {
font-size: 80px;
color: $color-text-1;
}
.text {
margin-bottom: $padding;
font-size: $font-size-body-3;
color: $color-text-2;
}
}
</style>
+55 -55
View File
@@ -1,55 +1,55 @@
<template>
<div class="page-404">
<div>
<s-svg-icon name="网络断开" :size="500" />
</div>
<div class="prompt">
<div class="title">500</div>
<div class="text">抱歉,无网络连接~</div>
<a-button type="primary" v-throttle="onBack">立即返回</a-button>
</div>
</div>
</template>
<script setup lang="ts">
import { Message } from "@arco-design/web-vue";
import { useRouter } from "vue-router";
const router = useRouter();
const onBack = () => {
if (!navigator.onLine) {
Message.error("网络未连接");
} else {
if (window.history.state.back !== null) {
router.replace(window.history.state.back);
} else {
router.replace("/login");
}
}
};
</script>
<style lang="scss" scoped>
.page-404 {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
padding: $padding;
overflow: hidden;
.prompt {
row-gap: $padding;
width: 250px;
}
.title {
font-size: 80px;
color: $color-text-1;
}
.text {
margin-bottom: $padding;
font-size: $font-size-body-3;
color: $color-text-2;
}
}
</style>
<template>
<div class="page-404">
<div>
<s-svg-icon name="网络断开" :size="500" />
</div>
<div class="prompt">
<div class="title">500</div>
<div class="text">抱歉,无网络连接~</div>
<a-button type="primary" v-throttle="onBack">立即返回</a-button>
</div>
</div>
</template>
<script setup lang="ts">
import { Message } from "@arco-design/web-vue";
import { useRouter } from "vue-router";
const router = useRouter();
const onBack = () => {
if (!navigator.onLine) {
Message.error("网络未连接");
} else {
if (window.history.state.back !== null) {
router.replace(window.history.state.back);
} else {
router.replace("/login");
}
}
};
</script>
<style lang="scss" scoped>
.page-404 {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
padding: $padding;
overflow: hidden;
.prompt {
row-gap: $padding;
width: 250px;
}
.title {
font-size: 80px;
color: $color-text-1;
}
.text {
margin-bottom: $padding;
font-size: $font-size-body-3;
color: $color-text-2;
}
}
</style>
+192 -192
View File
@@ -1,192 +1,192 @@
<template>
<div class="analysis-chart" :class="{ empty: isEmpty }" ref="dailyAnalysis">
<a-empty v-if="isEmpty" description="暂无交易数据" />
</div>
</template>
<script setup lang="ts">
import { default as VChart } from "@visactor/vchart";
const props = defineProps<{
homeData: any;
}>();
const dailyAnalysis = ref();
const isEmpty = ref(false);
let vchart: any = null;
let resizeObserver: ResizeObserver | null = null;
let initTimer: ReturnType<typeof setTimeout> | null = null;
const releaseChart = () => {
if (vchart) {
vchart.release();
vchart = null;
}
};
const scheduleInit = (delay = 0) => {
if (initTimer) {
clearTimeout(initTimer);
}
initTimer = setTimeout(() => {
initTimer = null;
init();
}, delay);
};
const init = async (retryCount = 0) => {
try {
if (!props.homeData?.token_map || !dailyAnalysis.value) return;
const tokenMap = props.homeData.token_map;
if (typeof tokenMap !== "object" || tokenMap === null) return;
const totalAmount = Object.values(tokenMap).reduce((sum: number, value: any) => {
const numValue = Number(value);
return sum + (isNaN(numValue) ? 0 : numValue);
}, 0);
if (totalAmount === 0) {
releaseChart();
isEmpty.value = true;
return;
}
const chartData = Object.entries(tokenMap)
.map(([token, amount]) => {
const numAmount = Number(amount);
if (isNaN(numAmount) || numAmount <= 0) return null;
const percentage = (numAmount / totalAmount) * 100;
return {
type: token,
value: Number(percentage.toFixed(2)),
amount: Number(numAmount.toFixed(2))
};
})
.filter(item => item !== null);
if (chartData.length === 0) {
releaseChart();
isEmpty.value = true;
return;
}
isEmpty.value = false;
await nextTick();
const containerWidth = dailyAnalysis.value?.clientWidth || 0;
const containerHeight = dailyAnalysis.value?.clientHeight || 0;
if ((!containerWidth || !containerHeight) && retryCount < 8) {
setTimeout(() => init(retryCount + 1), 100);
return;
}
releaseChart();
const colorMap = {
USDT: "#1E90FF",
USDC: "#32CD32",
TRX: "#FF4500",
BNB: "#F5A623",
ETH: "#722ED1"
};
const spec = {
type: "pie",
data: [{ id: "dailyAnalysisData", values: chartData }],
outerRadius: 0.8,
innerRadius: 0.5,
padAngle: 0.6,
valueField: "value",
categoryField: "type",
color: {
type: "ordinal",
domain: chartData.map(item => item.type),
range: chartData.map(item => colorMap[item.type as keyof typeof colorMap] || "#666666")
},
pie: {
style: { cornerRadius: 0 },
state: {
hover: { outerRadius: 0.85, stroke: "#fff", lineWidth: 1 },
selected: { outerRadius: 0.85, stroke: "#fff", lineWidth: 1 }
}
},
legends: { visible: true, orient: "left" },
label: { visible: true, content: "{type}: {value}%" },
tooltip: {
mark: {
content: [
{
key: (datum: any) => datum["type"],
value: (datum: any) => `${datum["value"]}% (${datum["amount"]})`
}
]
}
},
animation: false,
width: containerWidth || 400,
height: containerHeight || 300
};
if (dailyAnalysis.value?.isConnected) {
vchart = new VChart(spec as any, { dom: dailyAnalysis.value });
vchart.renderSync();
}
} catch (error) {
console.error("分析图表初始化错误:", error);
releaseChart();
}
};
watch(
() => props.homeData,
newData => {
try {
if (newData?.token_map) scheduleInit(120);
} catch (error) {
console.error("分析图表更新失败:", error);
}
},
{ immediate: true, deep: true }
);
onMounted(() => {
try {
if (typeof ResizeObserver !== "undefined" && dailyAnalysis.value) {
resizeObserver = new ResizeObserver(() => scheduleInit(120));
resizeObserver.observe(dailyAnalysis.value);
}
if (props.homeData?.token_map) scheduleInit(160);
} catch (error) {
console.error("分析图表初始化失败:", error);
}
});
onUnmounted(() => {
try {
if (initTimer) {
clearTimeout(initTimer);
initTimer = null;
}
resizeObserver?.disconnect();
resizeObserver = null;
releaseChart();
} catch (error) {
console.error("清理图表失败:", error);
}
});
</script>
<style lang="scss" scoped>
.analysis-chart {
width: 100%;
height: 100%;
min-height: 300px;
&.empty {
display: flex;
align-items: center;
justify-content: center;
}
}
</style>
<template>
<div class="analysis-chart" :class="{ empty: isEmpty }" ref="dailyAnalysis">
<a-empty v-if="isEmpty" description="暂无交易数据" />
</div>
</template>
<script setup lang="ts">
import { default as VChart } from "@visactor/vchart";
const props = defineProps<{
homeData: any;
}>();
const dailyAnalysis = ref();
const isEmpty = ref(false);
let vchart: any = null;
let resizeObserver: ResizeObserver | null = null;
let initTimer: ReturnType<typeof setTimeout> | null = null;
const releaseChart = () => {
if (vchart) {
vchart.release();
vchart = null;
}
};
const scheduleInit = (delay = 0) => {
if (initTimer) {
clearTimeout(initTimer);
}
initTimer = setTimeout(() => {
initTimer = null;
init();
}, delay);
};
const init = async (retryCount = 0) => {
try {
if (!props.homeData?.token_map || !dailyAnalysis.value) return;
const tokenMap = props.homeData.token_map;
if (typeof tokenMap !== "object" || tokenMap === null) return;
const totalAmount = Object.values(tokenMap).reduce((sum: number, value: any) => {
const numValue = Number(value);
return sum + (isNaN(numValue) ? 0 : numValue);
}, 0);
if (totalAmount === 0) {
releaseChart();
isEmpty.value = true;
return;
}
const chartData = Object.entries(tokenMap)
.map(([token, amount]) => {
const numAmount = Number(amount);
if (isNaN(numAmount) || numAmount <= 0) return null;
const percentage = (numAmount / totalAmount) * 100;
return {
type: token,
value: Number(percentage.toFixed(2)),
amount: Number(numAmount.toFixed(2))
};
})
.filter(item => item !== null);
if (chartData.length === 0) {
releaseChart();
isEmpty.value = true;
return;
}
isEmpty.value = false;
await nextTick();
const containerWidth = dailyAnalysis.value?.clientWidth || 0;
const containerHeight = dailyAnalysis.value?.clientHeight || 0;
if ((!containerWidth || !containerHeight) && retryCount < 8) {
setTimeout(() => init(retryCount + 1), 100);
return;
}
releaseChart();
const colorMap = {
USDT: "#1E90FF",
USDC: "#32CD32",
TRX: "#FF4500",
BNB: "#F5A623",
ETH: "#722ED1"
};
const spec = {
type: "pie",
data: [{ id: "dailyAnalysisData", values: chartData }],
outerRadius: 0.8,
innerRadius: 0.5,
padAngle: 0.6,
valueField: "value",
categoryField: "type",
color: {
type: "ordinal",
domain: chartData.map(item => item.type),
range: chartData.map(item => colorMap[item.type as keyof typeof colorMap] || "#666666")
},
pie: {
style: { cornerRadius: 0 },
state: {
hover: { outerRadius: 0.85, stroke: "#fff", lineWidth: 1 },
selected: { outerRadius: 0.85, stroke: "#fff", lineWidth: 1 }
}
},
legends: { visible: true, orient: "left" },
label: { visible: true, content: "{type}: {value}%" },
tooltip: {
mark: {
content: [
{
key: (datum: any) => datum["type"],
value: (datum: any) => `${datum["value"]}% (${datum["amount"]})`
}
]
}
},
animation: false,
width: containerWidth || 400,
height: containerHeight || 300
};
if (dailyAnalysis.value?.isConnected) {
vchart = new VChart(spec as any, { dom: dailyAnalysis.value });
vchart.renderSync();
}
} catch (error) {
console.error("分析图表初始化错误:", error);
releaseChart();
}
};
watch(
() => props.homeData,
newData => {
try {
if (newData?.token_map) scheduleInit(120);
} catch (error) {
console.error("分析图表更新失败:", error);
}
},
{ immediate: true, deep: true }
);
onMounted(() => {
try {
if (typeof ResizeObserver !== "undefined" && dailyAnalysis.value) {
resizeObserver = new ResizeObserver(() => scheduleInit(120));
resizeObserver.observe(dailyAnalysis.value);
}
if (props.homeData?.token_map) scheduleInit(160);
} catch (error) {
console.error("分析图表初始化失败:", error);
}
});
onUnmounted(() => {
try {
if (initTimer) {
clearTimeout(initTimer);
initTimer = null;
}
resizeObserver?.disconnect();
resizeObserver = null;
releaseChart();
} catch (error) {
console.error("清理图表失败:", error);
}
});
</script>
<style lang="scss" scoped>
.analysis-chart {
width: 100%;
height: 100%;
min-height: 300px;
&.empty {
display: flex;
align-items: center;
justify-content: center;
}
}
</style>
+87 -87
View File
@@ -1,87 +1,87 @@
<template>
<div class="data-box">
<div class="sell-histogram">
<div>
<span class="data-title">收款趋势</span>
<span class="data-subtext">单位: 天</span>
</div>
<div class="chart-body">
<HistogramChart :home-data="props.homeData" />
</div>
</div>
<div class="daily-analysis">
<div>
<span class="data-title">交易占比</span>
</div>
<div class="chart-body">
<AnalysisChart :home-data="props.homeData" />
</div>
</div>
</div>
</template>
<script setup lang="ts">
import HistogramChart from "@/views/home/components/histogram-chart.vue";
import AnalysisChart from "@/views/home/components/analysis-chart.vue";
const props = defineProps<{
homeData: any;
}>();
</script>
<style lang="scss" scoped>
.data-box {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
margin-top: calc($padding * 2);
.sell-histogram,
.daily-analysis {
display: flex;
flex-direction: column;
height: 400px;
padding-bottom: $padding;
min-width: 0;
}
.sell-histogram {
width: 100%;
}
.daily-analysis {
width: 100%;
}
.chart-body {
flex: 1;
min-height: 0;
min-width: 0;
}
.data-title {
font-size: $font-size-body-3;
color: $color-text-1;
}
.data-subtext {
margin-left: $margin-text;
font-size: $font-size-body-2;
color: $color-text-2;
}
}
@media screen and (min-width: $xxl) {
.data-box {
.sell-histogram {
width: calc(100% - 600px - $padding);
}
.daily-analysis {
width: 600px;
margin-left: $padding;
}
}
}
</style>
<template>
<div class="data-box">
<div class="sell-histogram">
<div>
<span class="data-title">收款趋势</span>
<span class="data-subtext">单位: 天</span>
</div>
<div class="chart-body">
<HistogramChart :home-data="props.homeData" />
</div>
</div>
<div class="daily-analysis">
<div>
<span class="data-title">交易占比</span>
</div>
<div class="chart-body">
<AnalysisChart :home-data="props.homeData" />
</div>
</div>
</div>
</template>
<script setup lang="ts">
import HistogramChart from "@/views/home/components/histogram-chart.vue";
import AnalysisChart from "@/views/home/components/analysis-chart.vue";
const props = defineProps<{
homeData: any;
}>();
</script>
<style lang="scss" scoped>
.data-box {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
margin-top: calc($padding * 2);
.sell-histogram,
.daily-analysis {
display: flex;
flex-direction: column;
height: 400px;
padding-bottom: $padding;
min-width: 0;
}
.sell-histogram {
width: 100%;
}
.daily-analysis {
width: 100%;
}
.chart-body {
flex: 1;
min-height: 0;
min-width: 0;
}
.data-title {
font-size: $font-size-body-3;
color: $color-text-1;
}
.data-subtext {
margin-left: $margin-text;
font-size: $font-size-body-2;
color: $color-text-2;
}
}
@media screen and (min-width: $xxl) {
.data-box {
.sell-histogram {
width: calc(100% - 600px - $padding);
}
.daily-analysis {
width: 600px;
margin-left: $padding;
}
}
}
</style>
+145 -145
View File
@@ -1,145 +1,145 @@
<template>
<div class="shortcut-box">
<div class="box-title">
<div>数据汇总</div>
</div>
<a-divider :margin="16" />
<a-grid class="finance-card" :cols="{ xs: 1, sm: 2, lg: 3, xl: 5 }" :col-gap="16" :row-gap="20">
<a-grid-item v-for="(item, index) in financeData" :key="index">
<a-card hoverable class="finance-a-card" :class="'animated-fade-up-' + index">
<div class="finance-nav">
<div class="tag-dot" :style="{ border: `3px solid ${item.color}` }"></div>
<span class="finance-nav-title">{{ item.title }}</span>
</div>
<div class="finance-value">{{ item.value }}</div>
<div class="finance-sub">
<span>{{ item.subLabel }}</span>
<span>{{ item.subValue }}</span>
</div>
</a-card>
</a-grid-item>
</a-grid>
</div>
</template>
<script setup lang="ts">
const props = defineProps<{
homeData: any;
}>();
const formatAmount = (value: any) => Number(value || 0).toFixed(2);
const formatPeriod = (from?: string, to?: string) => {
if (!from || !to) return "--";
return `${from.slice(5, 10).replace("-", "/")} - ${to.slice(5, 10).replace("-", "/")}`;
};
const buildFinanceData = (data: any) => {
const kpi = data?.kpi || {};
return [
{
id: 1,
title: "订单总数",
value: kpi.orders_total || 0,
subLabel: "已支付订单:",
subValue: kpi.orders_success || 0,
color: "#165DFF"
},
{
id: 2,
title: "收款金额",
value: formatAmount(kpi.gmv_paid),
subLabel: "支付成功率:",
subValue: `${formatAmount(kpi.order_success_rate)}%`,
color: "#14A058"
},
{
id: 3,
title: "待付订单",
value: kpi.orders_pending || 0,
subLabel: "确认中订单:",
subValue: kpi.orders_confirming || 0,
color: "#F5A623"
},
{
id: 4,
title: "失败订单",
value: kpi.orders_failed || 0,
subLabel: "通知失败:",
subValue: kpi.notify_failed || 0,
color: "#E33E38"
},
{
id: 5,
title: "统计周期",
value: formatPeriod(data?.from, data?.to),
subLabel: "",
subValue: data?.timezone || "--",
color: "#722ED1"
}
];
};
const financeData = ref(buildFinanceData(props.homeData));
watch(
() => props.homeData,
newData => {
financeData.value = buildFinanceData(newData);
},
{ immediate: true }
);
</script>
<style lang="scss" scoped>
.shortcut-box {
.card-box {
margin-bottom: $padding;
.shortcut-card-label {
width: 100px;
margin-left: 20px;
font-size: $font-size-body-3;
color: $color-text-2;
}
}
.card-middling {
width: 200px;
}
.row-center {
display: flex;
align-items: center;
justify-content: center;
}
}
.box-title {
display: flex;
align-items: center;
justify-content: space-between;
font-size: $font-size-body-3;
color: $color-text-1;
}
.finance-a-card {
min-height: 126px;
}
.finance-value {
margin: 14px 0 0 16px;
color: $color-text-1;
font-size: 24px;
line-height: 32px;
font-weight: 600;
word-break: break-word;
}
.finance-sub {
display: flex;
gap: 6px;
align-items: center;
margin: 8px 0 0 16px;
color: $color-text-2;
font-size: 13px;
line-height: 18px;
white-space: nowrap;
}
.margin-left-text {
margin-left: $margin-text;
}
</style>
<template>
<div class="shortcut-box">
<div class="box-title">
<div>数据汇总</div>
</div>
<a-divider :margin="16" />
<a-grid class="finance-card" :cols="{ xs: 1, sm: 2, lg: 3, xl: 5 }" :col-gap="16" :row-gap="20">
<a-grid-item v-for="(item, index) in financeData" :key="index">
<a-card hoverable class="finance-a-card" :class="'animated-fade-up-' + index">
<div class="finance-nav">
<div class="tag-dot" :style="{ border: `3px solid ${item.color}` }"></div>
<span class="finance-nav-title">{{ item.title }}</span>
</div>
<div class="finance-value">{{ item.value }}</div>
<div class="finance-sub">
<span>{{ item.subLabel }}</span>
<span>{{ item.subValue }}</span>
</div>
</a-card>
</a-grid-item>
</a-grid>
</div>
</template>
<script setup lang="ts">
const props = defineProps<{
homeData: any;
}>();
const formatAmount = (value: any) => Number(value || 0).toFixed(2);
const formatPeriod = (from?: string, to?: string) => {
if (!from || !to) return "--";
return `${from.slice(5, 10).replace("-", "/")} - ${to.slice(5, 10).replace("-", "/")}`;
};
const buildFinanceData = (data: any) => {
const kpi = data?.kpi || {};
return [
{
id: 1,
title: "订单总数",
value: kpi.orders_total || 0,
subLabel: "已支付订单:",
subValue: kpi.orders_success || 0,
color: "#165DFF"
},
{
id: 2,
title: "收款金额",
value: formatAmount(kpi.gmv_paid),
subLabel: "支付成功率:",
subValue: `${formatAmount(kpi.order_success_rate)}%`,
color: "#14A058"
},
{
id: 3,
title: "待付订单",
value: kpi.orders_pending || 0,
subLabel: "确认中订单:",
subValue: kpi.orders_confirming || 0,
color: "#F5A623"
},
{
id: 4,
title: "失败订单",
value: kpi.orders_failed || 0,
subLabel: "通知失败:",
subValue: kpi.notify_failed || 0,
color: "#E33E38"
},
{
id: 5,
title: "统计周期",
value: formatPeriod(data?.from, data?.to),
subLabel: "",
subValue: data?.timezone || "--",
color: "#722ED1"
}
];
};
const financeData = ref(buildFinanceData(props.homeData));
watch(
() => props.homeData,
newData => {
financeData.value = buildFinanceData(newData);
},
{ immediate: true }
);
</script>
<style lang="scss" scoped>
.shortcut-box {
.card-box {
margin-bottom: $padding;
.shortcut-card-label {
width: 100px;
margin-left: 20px;
font-size: $font-size-body-3;
color: $color-text-2;
}
}
.card-middling {
width: 200px;
}
.row-center {
display: flex;
align-items: center;
justify-content: center;
}
}
.box-title {
display: flex;
align-items: center;
justify-content: space-between;
font-size: $font-size-body-3;
color: $color-text-1;
}
.finance-a-card {
min-height: 126px;
}
.finance-value {
margin: 14px 0 0 16px;
color: $color-text-1;
font-size: 24px;
line-height: 32px;
font-weight: 600;
word-break: break-word;
}
.finance-sub {
display: flex;
gap: 6px;
align-items: center;
margin: 8px 0 0 16px;
color: $color-text-2;
font-size: 13px;
line-height: 18px;
white-space: nowrap;
}
.margin-left-text {
margin-left: $margin-text;
}
</style>
+222 -222
View File
@@ -1,222 +1,222 @@
<template>
<div class="histogram-scroll" :class="{ empty: isEmpty, scrollable: isScrollable }" ref="histogramScroll">
<a-empty v-if="isEmpty" description="暂无订单数据" />
<div v-show="!isEmpty" class="histogram-canvas" ref="sellHistogram" :style="{ width: `${chartWidth}px` }"></div>
</div>
</template>
<script setup lang="ts">
import { default as VChart } from "@visactor/vchart";
const props = defineProps<{
homeData: any;
}>();
const sellHistogram = ref();
const histogramScroll = ref();
const chartWidth = ref(0);
const isEmpty = ref(false);
const isScrollable = ref(false);
let vchart: any = null;
let resizeObserver: ResizeObserver | null = null;
let initTimer: ReturnType<typeof setTimeout> | null = null;
const releaseChart = () => {
if (vchart) {
vchart.release();
vchart = null;
}
};
const scheduleInit = (delay = 0) => {
if (initTimer) {
clearTimeout(initTimer);
}
initTimer = setTimeout(() => {
initTimer = null;
init();
}, delay);
};
const getCssVarRgb = (name: string, fallback: string) => {
const bodyValue = getComputedStyle(document.body).getPropertyValue(name).trim();
const value = bodyValue || getComputedStyle(document.documentElement).getPropertyValue(name).trim();
return value ? `rgb(${value})` : fallback;
};
const getThemeColors = () => {
return [getCssVarRgb("--primary-6", "#165dff"), getCssVarRgb("--success-6", "#00b42a")];
};
const init = async (retryCount = 0) => {
try {
if (!props.homeData?.points || !sellHistogram.value || !histogramScroll.value) return;
const points = props.homeData.points;
if (!Array.isArray(points)) return;
const gmvPaidByDate: Record<string, string> = {};
const chartData = points.flatMap(point => {
const date = String(point.date || "")
.slice(5)
.replace("-", "/");
gmvPaidByDate[date] = Number(point.gmv_paid || 0).toFixed(2);
return [
{
date,
type: "订单总数",
value: Number(point.orders_total || 0)
},
{
date,
type: "已支付订单",
value: Number(point.orders_paid ?? point.orders_success ?? 0)
}
];
});
if (chartData.length === 0) return;
const hasOrderData = chartData.some(item => item.value > 0);
if (!hasOrderData) {
releaseChart();
isEmpty.value = true;
isScrollable.value = false;
return;
}
isEmpty.value = false;
await nextTick();
const containerWidth = histogramScroll.value?.clientWidth || 0;
const containerHeight = sellHistogram.value?.clientHeight || histogramScroll.value?.clientHeight || 0;
if ((!containerWidth || !containerHeight) && retryCount < 8) {
setTimeout(() => init(retryCount + 1), 100);
return;
}
const renderWidth = containerWidth || 400;
const renderHeight = containerHeight || 300;
isScrollable.value = points.length > 7;
chartWidth.value = isScrollable.value ? Math.max(renderWidth, points.length * 44) : renderWidth;
await nextTick();
releaseChart();
const spec = {
type: "bar",
data: [{ id: "sellHistogramData", values: chartData }],
xField: ["date", "type"],
yField: "value",
seriesField: "type",
barWidth: 9,
barGapInGroup: 2,
legends: { visible: true, orient: "top", position: "middle" },
color: {
type: "ordinal",
domain: ["订单总数", "已支付订单"],
range: getThemeColors()
},
axes: [
{
orient: "bottom",
label: {
visible: true,
formatMethod: (value: string) => (gmvPaidByDate[value] ? [value, gmvPaidByDate[value]] : value),
style: {
fontSize: 10,
lineHeight: 13
}
},
showAllGroupLayers: false
},
{ orient: "left", label: { visible: true }, min: 0 }
],
tooltip: {
mark: {
content: [
{
key: (datum: any) => datum["type"],
value: (datum: any) => datum["value"]
}
]
}
},
animation: false,
width: chartWidth.value || renderWidth,
height: renderHeight
};
if (sellHistogram.value?.isConnected) {
vchart = new VChart(spec as any, { dom: sellHistogram.value });
vchart.renderSync();
}
} catch (error) {
console.error("图表初始化错误:", error);
releaseChart();
}
};
watch(
() => props.homeData,
newData => {
try {
if (newData?.points) scheduleInit(120);
} catch (error) {
console.error("图表更新失败:", error);
}
},
{ immediate: true, deep: true }
);
onMounted(() => {
try {
if (typeof ResizeObserver !== "undefined" && histogramScroll.value) {
resizeObserver = new ResizeObserver(() => scheduleInit(120));
resizeObserver.observe(histogramScroll.value);
}
if (props.homeData?.points) scheduleInit(160);
} catch (error) {
console.error("图表初始化失败:", error);
}
});
onUnmounted(() => {
try {
if (initTimer) {
clearTimeout(initTimer);
initTimer = null;
}
resizeObserver?.disconnect();
resizeObserver = null;
releaseChart();
} catch (error) {
console.error("清理图表失败:", error);
}
});
</script>
<style lang="scss" scoped>
.histogram-scroll {
width: 100%;
height: 100%;
overflow-x: hidden;
overflow-y: hidden;
&.scrollable {
overflow-x: auto;
}
&.empty {
display: flex;
align-items: center;
justify-content: center;
}
}
.histogram-canvas {
height: 100%;
min-width: 100%;
min-height: 300px;
}
</style>
<template>
<div class="histogram-scroll" :class="{ empty: isEmpty, scrollable: isScrollable }" ref="histogramScroll">
<a-empty v-if="isEmpty" description="暂无订单数据" />
<div v-show="!isEmpty" class="histogram-canvas" ref="sellHistogram" :style="{ width: `${chartWidth}px` }"></div>
</div>
</template>
<script setup lang="ts">
import { default as VChart } from "@visactor/vchart";
const props = defineProps<{
homeData: any;
}>();
const sellHistogram = ref();
const histogramScroll = ref();
const chartWidth = ref(0);
const isEmpty = ref(false);
const isScrollable = ref(false);
let vchart: any = null;
let resizeObserver: ResizeObserver | null = null;
let initTimer: ReturnType<typeof setTimeout> | null = null;
const releaseChart = () => {
if (vchart) {
vchart.release();
vchart = null;
}
};
const scheduleInit = (delay = 0) => {
if (initTimer) {
clearTimeout(initTimer);
}
initTimer = setTimeout(() => {
initTimer = null;
init();
}, delay);
};
const getCssVarRgb = (name: string, fallback: string) => {
const bodyValue = getComputedStyle(document.body).getPropertyValue(name).trim();
const value = bodyValue || getComputedStyle(document.documentElement).getPropertyValue(name).trim();
return value ? `rgb(${value})` : fallback;
};
const getThemeColors = () => {
return [getCssVarRgb("--primary-6", "#165dff"), getCssVarRgb("--success-6", "#00b42a")];
};
const init = async (retryCount = 0) => {
try {
if (!props.homeData?.points || !sellHistogram.value || !histogramScroll.value) return;
const points = props.homeData.points;
if (!Array.isArray(points)) return;
const gmvPaidByDate: Record<string, string> = {};
const chartData = points.flatMap(point => {
const date = String(point.date || "")
.slice(5)
.replace("-", "/");
gmvPaidByDate[date] = Number(point.gmv_paid || 0).toFixed(2);
return [
{
date,
type: "订单总数",
value: Number(point.orders_total || 0)
},
{
date,
type: "已支付订单",
value: Number(point.orders_paid ?? point.orders_success ?? 0)
}
];
});
if (chartData.length === 0) return;
const hasOrderData = chartData.some(item => item.value > 0);
if (!hasOrderData) {
releaseChart();
isEmpty.value = true;
isScrollable.value = false;
return;
}
isEmpty.value = false;
await nextTick();
const containerWidth = histogramScroll.value?.clientWidth || 0;
const containerHeight = sellHistogram.value?.clientHeight || histogramScroll.value?.clientHeight || 0;
if ((!containerWidth || !containerHeight) && retryCount < 8) {
setTimeout(() => init(retryCount + 1), 100);
return;
}
const renderWidth = containerWidth || 400;
const renderHeight = containerHeight || 300;
isScrollable.value = points.length > 7;
chartWidth.value = isScrollable.value ? Math.max(renderWidth, points.length * 44) : renderWidth;
await nextTick();
releaseChart();
const spec = {
type: "bar",
data: [{ id: "sellHistogramData", values: chartData }],
xField: ["date", "type"],
yField: "value",
seriesField: "type",
barWidth: 9,
barGapInGroup: 2,
legends: { visible: true, orient: "top", position: "middle" },
color: {
type: "ordinal",
domain: ["订单总数", "已支付订单"],
range: getThemeColors()
},
axes: [
{
orient: "bottom",
label: {
visible: true,
formatMethod: (value: string) => (gmvPaidByDate[value] ? [value, gmvPaidByDate[value]] : value),
style: {
fontSize: 10,
lineHeight: 13
}
},
showAllGroupLayers: false
},
{ orient: "left", label: { visible: true }, min: 0 }
],
tooltip: {
mark: {
content: [
{
key: (datum: any) => datum["type"],
value: (datum: any) => datum["value"]
}
]
}
},
animation: false,
width: chartWidth.value || renderWidth,
height: renderHeight
};
if (sellHistogram.value?.isConnected) {
vchart = new VChart(spec as any, { dom: sellHistogram.value });
vchart.renderSync();
}
} catch (error) {
console.error("图表初始化错误:", error);
releaseChart();
}
};
watch(
() => props.homeData,
newData => {
try {
if (newData?.points) scheduleInit(120);
} catch (error) {
console.error("图表更新失败:", error);
}
},
{ immediate: true, deep: true }
);
onMounted(() => {
try {
if (typeof ResizeObserver !== "undefined" && histogramScroll.value) {
resizeObserver = new ResizeObserver(() => scheduleInit(120));
resizeObserver.observe(histogramScroll.value);
}
if (props.homeData?.points) scheduleInit(160);
} catch (error) {
console.error("图表初始化失败:", error);
}
});
onUnmounted(() => {
try {
if (initTimer) {
clearTimeout(initTimer);
initTimer = null;
}
resizeObserver?.disconnect();
resizeObserver = null;
releaseChart();
} catch (error) {
console.error("清理图表失败:", error);
}
});
</script>
<style lang="scss" scoped>
.histogram-scroll {
width: 100%;
height: 100%;
overflow-x: hidden;
overflow-y: hidden;
&.scrollable {
overflow-x: auto;
}
&.empty {
display: flex;
align-items: center;
justify-content: center;
}
}
.histogram-canvas {
height: 100%;
min-width: 100%;
min-height: 300px;
}
</style>
+273 -273
View File
@@ -1,273 +1,273 @@
<template>
<div class="snow-page">
<div class="home-page">
<div class="dashboard-toolbar">
<!-- 法币选择器 -->
<div class="fiat-selector">
<span class="label">交易法币:</span>
<div class="fiat-options">
<div
v-for="item in fiatOptions"
:key="item.value"
class="fiat-option"
:class="{ active: fiat === item.value }"
@click="handleFiatChange(item.value)"
>
<span class="currency-symbol">{{ item.symbol }}</span>
<span class="currency-name">{{ item.label }}</span>
</div>
</div>
</div>
<div class="range-actions">
<a-range-picker
v-if="range === 'custom'"
v-model="customDates"
format="YYYY-MM-DD"
style="width: 240px"
@change="handleCustomDateChange"
/>
<a-select v-model="range" style="width: 132px" @change="handleRangeChange">
<a-option v-for="item in rangeOptions" :key="item.value" :value="item.value">
{{ item.label }}
</a-option>
</a-select>
<a-button type="primary" :loading="loading" @click="forceRefresh">
<template #icon><icon-refresh /></template>
强制刷新
</a-button>
</div>
</div>
<!-- 财务指标 -->
<Finance :home-data="home" />
<!-- 数据图 -->
<DataBox :home-data="home" />
</div>
</div>
</template>
<script setup lang="ts">
import Finance from "@/views/home/components/finance.vue";
import DataBox from "@/views/home/components/data-box.vue";
import { getDashboardHomeAPI } from "@/api/modules/home/index";
const fiat = ref("CNY");
const range = ref("7d");
const customDates = ref<any[]>([]);
const home = ref<any>(null);
const loading = ref(false);
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "Asia/Shanghai";
let dashboardRetryTimer: ReturnType<typeof setTimeout> | null = null;
const fiatOptions = ref([
{ value: "CNY", label: "人民币", symbol: "¥" },
{ value: "USD", label: "美元", symbol: "$" },
{ value: "EUR", label: "欧元", symbol: "€" },
{ value: "GBP", label: "英镑", symbol: "£" },
{ value: "JPY", label: "日元", symbol: "¥" }
]);
const rangeOptions = [
{ value: "today", label: "今天" },
{ value: "7d", label: "最近 7 天" },
{ value: "30d", label: "最近 30 天" },
{ value: "custom", label: "自定义" }
];
const clearDashboardRetry = () => {
if (dashboardRetryTimer) {
clearTimeout(dashboardRetryTimer);
dashboardRetryTimer = null;
}
};
const getDashboardHome = async (force = false, retryCount = 0) => {
if (range.value === "custom" && (!Array.isArray(customDates.value) || customDates.value.length !== 2)) return;
if (retryCount === 0) {
clearDashboardRetry();
}
loading.value = true;
try {
const params: any = {
range: range.value,
tz: timezone,
fiat: fiat.value,
force
};
if (range.value === "custom") {
params.from = customDates.value[0];
params.to = customDates.value[1];
}
const data = await getDashboardHomeAPI(params);
if (!data?.data) {
throw new Error("仪表盘数据为空");
}
home.value = data.data;
} catch (error) {
if (retryCount < 3) {
dashboardRetryTimer = setTimeout(() => {
getDashboardHome(force, retryCount + 1);
}, (retryCount + 1) * 1000);
return;
}
console.error("获取首页统计失败:", error);
} finally {
loading.value = false;
}
};
// 处理法币切换
const handleFiatChange = (value: string) => {
fiat.value = value;
getDashboardHome();
};
const handleRangeChange = () => {
if (range.value !== "custom") {
getDashboardHome();
}
};
const handleCustomDateChange = () => {
getDashboardHome();
};
const forceRefresh = () => {
getDashboardHome(true);
};
onMounted(() => {
getDashboardHome();
});
onUnmounted(() => {
clearDashboardRetry();
});
</script>
<style lang="scss" scoped>
.home-page {
padding: $padding;
background: $color-bg-1;
}
.dashboard-toolbar {
margin-bottom: 16px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
.fiat-selector {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 16px;
background: $color-bg-2;
border-radius: 8px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
border: 1px solid $color-border-2;
.label {
font-size: 13px;
font-weight: 500;
color: $color-text-2;
white-space: nowrap;
}
.fiat-options {
display: flex;
gap: 6px;
}
.fiat-option {
display: flex;
align-items: center;
gap: 4px;
padding: 6px 12px;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s ease;
border: 1px solid $color-border-2;
background: $color-fill-1;
min-width: 60px;
justify-content: center;
&:hover {
border-color: $color-primary;
background: rgb(var(--primary-1));
}
&.active {
background: $color-primary;
border-color: $color-primary;
color: #fff;
box-shadow: 0 2px 8px rgb(var(--primary-6) / 25%);
.currency-symbol,
.currency-name {
color: #fff;
}
}
.currency-symbol {
font-size: 14px;
font-weight: bold;
color: $color-primary;
}
.currency-name {
font-size: 11px;
color: $color-text-2;
font-weight: 500;
}
}
}
.range-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 10px;
margin-left: auto;
}
// 响应式设计
@media (max-width: 768px) {
.dashboard-toolbar {
align-items: stretch;
}
.fiat-selector {
flex-direction: column;
align-items: flex-start;
gap: 8px;
padding: 10px 12px;
.fiat-options {
width: 100%;
justify-content: space-between;
flex-wrap: wrap;
}
.fiat-option {
flex: 1;
min-width: auto;
margin-bottom: 4px;
}
}
.range-actions {
width: 100%;
flex-wrap: wrap;
justify-content: flex-start;
margin-left: 0;
}
}
</style>
<template>
<div class="snow-page">
<div class="home-page">
<div class="dashboard-toolbar">
<!-- 法币选择器 -->
<div class="fiat-selector">
<span class="label">交易法币:</span>
<div class="fiat-options">
<div
v-for="item in fiatOptions"
:key="item.value"
class="fiat-option"
:class="{ active: fiat === item.value }"
@click="handleFiatChange(item.value)"
>
<span class="currency-symbol">{{ item.symbol }}</span>
<span class="currency-name">{{ item.label }}</span>
</div>
</div>
</div>
<div class="range-actions">
<a-range-picker
v-if="range === 'custom'"
v-model="customDates"
format="YYYY-MM-DD"
style="width: 240px"
@change="handleCustomDateChange"
/>
<a-select v-model="range" style="width: 132px" @change="handleRangeChange">
<a-option v-for="item in rangeOptions" :key="item.value" :value="item.value">
{{ item.label }}
</a-option>
</a-select>
<a-button type="primary" :loading="loading" @click="forceRefresh">
<template #icon><icon-refresh /></template>
强制刷新
</a-button>
</div>
</div>
<!-- 财务指标 -->
<Finance :home-data="home" />
<!-- 数据图 -->
<DataBox :home-data="home" />
</div>
</div>
</template>
<script setup lang="ts">
import Finance from "@/views/home/components/finance.vue";
import DataBox from "@/views/home/components/data-box.vue";
import { getDashboardHomeAPI } from "@/api/modules/home/index";
const fiat = ref("CNY");
const range = ref("7d");
const customDates = ref<any[]>([]);
const home = ref<any>(null);
const loading = ref(false);
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "Asia/Shanghai";
let dashboardRetryTimer: ReturnType<typeof setTimeout> | null = null;
const fiatOptions = ref([
{ value: "CNY", label: "人民币", symbol: "¥" },
{ value: "USD", label: "美元", symbol: "$" },
{ value: "EUR", label: "欧元", symbol: "€" },
{ value: "GBP", label: "英镑", symbol: "£" },
{ value: "JPY", label: "日元", symbol: "¥" }
]);
const rangeOptions = [
{ value: "today", label: "今天" },
{ value: "7d", label: "最近 7 天" },
{ value: "30d", label: "最近 30 天" },
{ value: "custom", label: "自定义" }
];
const clearDashboardRetry = () => {
if (dashboardRetryTimer) {
clearTimeout(dashboardRetryTimer);
dashboardRetryTimer = null;
}
};
const getDashboardHome = async (force = false, retryCount = 0) => {
if (range.value === "custom" && (!Array.isArray(customDates.value) || customDates.value.length !== 2)) return;
if (retryCount === 0) {
clearDashboardRetry();
}
loading.value = true;
try {
const params: any = {
range: range.value,
tz: timezone,
fiat: fiat.value,
force
};
if (range.value === "custom") {
params.from = customDates.value[0];
params.to = customDates.value[1];
}
const data = await getDashboardHomeAPI(params);
if (!data?.data) {
throw new Error("仪表盘数据为空");
}
home.value = data.data;
} catch (error) {
if (retryCount < 3) {
dashboardRetryTimer = setTimeout(() => {
getDashboardHome(force, retryCount + 1);
}, (retryCount + 1) * 1000);
return;
}
console.error("获取首页统计失败:", error);
} finally {
loading.value = false;
}
};
// 处理法币切换
const handleFiatChange = (value: string) => {
fiat.value = value;
getDashboardHome();
};
const handleRangeChange = () => {
if (range.value !== "custom") {
getDashboardHome();
}
};
const handleCustomDateChange = () => {
getDashboardHome();
};
const forceRefresh = () => {
getDashboardHome(true);
};
onMounted(() => {
getDashboardHome();
});
onUnmounted(() => {
clearDashboardRetry();
});
</script>
<style lang="scss" scoped>
.home-page {
padding: $padding;
background: $color-bg-1;
}
.dashboard-toolbar {
margin-bottom: 16px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
.fiat-selector {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 16px;
background: $color-bg-2;
border-radius: 8px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
border: 1px solid $color-border-2;
.label {
font-size: 13px;
font-weight: 500;
color: $color-text-2;
white-space: nowrap;
}
.fiat-options {
display: flex;
gap: 6px;
}
.fiat-option {
display: flex;
align-items: center;
gap: 4px;
padding: 6px 12px;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s ease;
border: 1px solid $color-border-2;
background: $color-fill-1;
min-width: 60px;
justify-content: center;
&:hover {
border-color: $color-primary;
background: rgb(var(--primary-1));
}
&.active {
background: $color-primary;
border-color: $color-primary;
color: #fff;
box-shadow: 0 2px 8px rgb(var(--primary-6) / 25%);
.currency-symbol,
.currency-name {
color: #fff;
}
}
.currency-symbol {
font-size: 14px;
font-weight: bold;
color: $color-primary;
}
.currency-name {
font-size: 11px;
color: $color-text-2;
font-weight: 500;
}
}
}
.range-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 10px;
margin-left: auto;
}
// 响应式设计
@media (max-width: 768px) {
.dashboard-toolbar {
align-items: stretch;
}
.fiat-selector {
flex-direction: column;
align-items: flex-start;
gap: 8px;
padding: 10px 12px;
.fiat-options {
width: 100%;
justify-content: space-between;
flex-wrap: wrap;
}
.fiat-option {
flex: 1;
min-width: auto;
margin-bottom: 4px;
}
}
.range-actions {
width: 100%;
flex-wrap: wrap;
justify-content: flex-start;
margin-left: 0;
}
}
</style>
+39 -39
View File
@@ -1,39 +1,39 @@
<template>
<div class="banner_box">
<div class="banner_title">
<s-svg-icon name="snow" size="25" />
{{ title }}
</div>
<div class="banner_img">
<s-svg-icon name="数据时代" size="100%" />
</div>
</div>
</template>
<script setup lang="ts">
// 全局title
const title = import.meta.env.VITE_GLOB_APP_TITLE;
</script>
<style lang="scss" scoped>
.banner_box {
position: relative;
box-sizing: border-box;
display: flex;
flex-direction: column;
width: 650px;
height: 100%;
padding: 30px;
.banner_title {
position: absolute;
display: flex;
column-gap: $margin-text;
align-items: center;
font-size: $font-size-title-1;
font-weight: bold;
color: $color-primary;
}
.banner_img {
flex: 1;
}
}
</style>
<template>
<div class="banner_box">
<div class="banner_title">
<s-svg-icon name="snow" size="25" />
{{ title }}
</div>
<div class="banner_img">
<s-svg-icon name="数据时代" size="100%" />
</div>
</div>
</template>
<script setup lang="ts">
// 全局title
const title = import.meta.env.VITE_GLOB_APP_TITLE;
</script>
<style lang="scss" scoped>
.banner_box {
position: relative;
box-sizing: border-box;
display: flex;
flex-direction: column;
width: 650px;
height: 100%;
padding: 30px;
.banner_title {
position: absolute;
display: flex;
column-gap: $margin-text;
align-items: center;
font-size: $font-size-title-1;
font-weight: bold;
color: $color-primary;
}
.banner_img {
flex: 1;
}
}
</style>
+162 -162
View File
@@ -1,162 +1,162 @@
<template>
<div>
<div class="login_form_box">
<a-form :rules="rules" :model="form" layout="vertical" @submit="onSubmit">
<a-form-item field="username" :hide-asterisk="true">
<a-input v-model="form.username" allow-clear placeholder="请输入账号">
<template #prefix>
<icon-user />
</template>
</a-input>
</a-form-item>
<a-form-item field="password" :hide-asterisk="true">
<a-input-password v-model="form.password" allow-clear placeholder="请输入密码">
<template #prefix>
<icon-lock />
</template>
</a-input-password>
</a-form-item>
<a-form-item field="remember">
<div class="remember">
<a-checkbox v-model="form.remember">记住密码</a-checkbox>
<div class="forgot-password" @click="handleForgotPassword">忘记密码</div>
</div>
</a-form-item>
<a-form-item>
<a-button long type="primary" html-type="submit">登录</a-button>
</a-form-item>
</a-form>
</div>
</div>
</template>
<script setup lang="ts">
import { useRouter } from "vue-router";
import { useUserInfoStore } from "@/store/modules/user-info";
import { loginAPI } from "@/api/modules/user/index";
let userStores = useUserInfoStore();
const router = useRouter();
// 记住密码的存储key
const REMEMBER_KEY = "login_remember_info";
// 简单的加密解密函数
const encrypt = (str: string) => {
return btoa(encodeURIComponent(str));
};
const decrypt = (str: string) => {
try {
return decodeURIComponent(atob(str));
} catch {
return "";
}
};
const form = ref({
username: "",
password: "",
verifyCode: null,
remember: false
});
const rules = ref({
username: [
{
required: true,
message: "请输入账号"
}
],
password: [
{
required: true,
message: "请输入密码"
}
]
});
// 组件挂载时读取记住的密码
onMounted(() => {
const savedInfo = localStorage.getItem(REMEMBER_KEY);
if (savedInfo) {
try {
const { username, password, remember } = JSON.parse(savedInfo);
form.value.username = decrypt(username);
form.value.password = decrypt(password);
form.value.remember = remember;
} catch (error) {
console.error("读取记住的密码失败:", error);
localStorage.removeItem(REMEMBER_KEY);
}
}
});
// 提交表单
const onSubmit = async ({ errors }: any) => {
if (errors) return;
onLogin();
};
// 登录
const onLogin = async () => {
// 处理记住密码
if (form.value.remember) {
// 保存加密后的账号密码
const rememberInfo = {
username: encrypt(form.value.username),
password: encrypt(form.value.password),
remember: true
};
localStorage.setItem(REMEMBER_KEY, JSON.stringify(rememberInfo));
} else {
// 不记住密码时清除存储
localStorage.removeItem(REMEMBER_KEY);
}
// 登录
let res = await loginAPI(form.value);
userStores.token = res.data.token;
// 加载用户信息
await userStores.setAccount();
// // 加载路由信息
// await routeStore.initSetRouter();
arcoMessage("success", "登录成功");
// 跳转首页
router.replace("/home");
// 设置字典
// useSystemStore().setDictData();
};
// 忘记密码
const handleForgotPassword = () => {
window.open("https://github.com/v03413/BEpusdt", "_blank");
};
</script>
<style lang="scss" scoped>
.login_form_box {
margin-top: 28px;
.verifyCode {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
}
.remember {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
.forgot-password {
color: $color-primary;
cursor: pointer;
}
}
}
</style>
<template>
<div>
<div class="login_form_box">
<a-form :rules="rules" :model="form" layout="vertical" @submit="onSubmit">
<a-form-item field="username" :hide-asterisk="true">
<a-input v-model="form.username" allow-clear placeholder="请输入账号">
<template #prefix>
<icon-user />
</template>
</a-input>
</a-form-item>
<a-form-item field="password" :hide-asterisk="true">
<a-input-password v-model="form.password" allow-clear placeholder="请输入密码">
<template #prefix>
<icon-lock />
</template>
</a-input-password>
</a-form-item>
<a-form-item field="remember">
<div class="remember">
<a-checkbox v-model="form.remember">记住密码</a-checkbox>
<div class="forgot-password" @click="handleForgotPassword">忘记密码</div>
</div>
</a-form-item>
<a-form-item>
<a-button long type="primary" html-type="submit">登录</a-button>
</a-form-item>
</a-form>
</div>
</div>
</template>
<script setup lang="ts">
import { useRouter } from "vue-router";
import { useUserInfoStore } from "@/store/modules/user-info";
import { loginAPI } from "@/api/modules/user/index";
let userStores = useUserInfoStore();
const router = useRouter();
// 记住密码的存储key
const REMEMBER_KEY = "login_remember_info";
// 简单的加密解密函数
const encrypt = (str: string) => {
return btoa(encodeURIComponent(str));
};
const decrypt = (str: string) => {
try {
return decodeURIComponent(atob(str));
} catch {
return "";
}
};
const form = ref({
username: "",
password: "",
verifyCode: null,
remember: false
});
const rules = ref({
username: [
{
required: true,
message: "请输入账号"
}
],
password: [
{
required: true,
message: "请输入密码"
}
]
});
// 组件挂载时读取记住的密码
onMounted(() => {
const savedInfo = localStorage.getItem(REMEMBER_KEY);
if (savedInfo) {
try {
const { username, password, remember } = JSON.parse(savedInfo);
form.value.username = decrypt(username);
form.value.password = decrypt(password);
form.value.remember = remember;
} catch (error) {
console.error("读取记住的密码失败:", error);
localStorage.removeItem(REMEMBER_KEY);
}
}
});
// 提交表单
const onSubmit = async ({ errors }: any) => {
if (errors) return;
onLogin();
};
// 登录
const onLogin = async () => {
// 处理记住密码
if (form.value.remember) {
// 保存加密后的账号密码
const rememberInfo = {
username: encrypt(form.value.username),
password: encrypt(form.value.password),
remember: true
};
localStorage.setItem(REMEMBER_KEY, JSON.stringify(rememberInfo));
} else {
// 不记住密码时清除存储
localStorage.removeItem(REMEMBER_KEY);
}
// 登录
let res = await loginAPI(form.value);
userStores.token = res.data.token;
// 加载用户信息
await userStores.setAccount();
// // 加载路由信息
// await routeStore.initSetRouter();
arcoMessage("success", "登录成功");
// 跳转首页
router.replace("/home");
// 设置字典
// useSystemStore().setDictData();
};
// 忘记密码
const handleForgotPassword = () => {
window.open("https://github.com/v03413/BEpusdt", "_blank");
};
</script>
<style lang="scss" scoped>
.login_form_box {
margin-top: 28px;
.verifyCode {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
}
.remember {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
.forgot-password {
color: $color-primary;
cursor: pointer;
}
}
}
</style>
+60 -60
View File
@@ -1,60 +1,60 @@
<template>
<div class="container">
<div class="login">
<LoginBanner v-if="isPc" />
<div class="login_box">
<div class="login_title">Welcome Back</div>
<div class="login_title_desc">一款更好用的个人加密货币收款网关,助力出海需求!</div>
<LoginForm />
<!-- <div class="author">by 兔子先森</div> -->
</div>
</div>
</div>
</template>
<script setup lang="ts">
import LoginBanner from "@/views/login/components/login-banner.vue";
import LoginForm from "@/views/login/components/login-form.vue";
import { useDevicesSize } from "@/hooks/useDevicesSize";
const { isPc } = useDevicesSize();
</script>
<style lang="scss" scoped>
.container {
position: relative;
height: 100vh;
overflow: hidden;
.login {
position: absolute;
top: 50%;
left: 50%;
display: flex;
align-items: center;
max-width: 1000px;
height: 500px;
box-shadow: 0 0 8px 1px $color-fill-2;
transform: translate(-50%, -50%);
.login_box {
position: relative;
box-sizing: border-box;
width: 350px;
height: 100%;
padding: 40px 30px 30px;
.login_title {
margin-bottom: $margin-text;
font-size: $font-size-title-2;
color: $color-text-1;
}
.login_title_desc {
font-size: $font-size-body-1;
color: $color-text-3;
}
.author {
position: absolute;
bottom: 30px;
font-size: $font-size-body-1;
color: $color-text-4;
}
}
}
}
</style>
<template>
<div class="container">
<div class="login">
<LoginBanner v-if="isPc" />
<div class="login_box">
<div class="login_title">Welcome Back</div>
<div class="login_title_desc">一款更好用的个人加密货币收款网关,助力出海需求!</div>
<LoginForm />
<!-- <div class="author">by 兔子先森</div> -->
</div>
</div>
</div>
</template>
<script setup lang="ts">
import LoginBanner from "@/views/login/components/login-banner.vue";
import LoginForm from "@/views/login/components/login-form.vue";
import { useDevicesSize } from "@/hooks/useDevicesSize";
const { isPc } = useDevicesSize();
</script>
<style lang="scss" scoped>
.container {
position: relative;
height: 100vh;
overflow: hidden;
.login {
position: absolute;
top: 50%;
left: 50%;
display: flex;
align-items: center;
max-width: 1000px;
height: 500px;
box-shadow: 0 0 8px 1px $color-fill-2;
transform: translate(-50%, -50%);
.login_box {
position: relative;
box-sizing: border-box;
width: 350px;
height: 100%;
padding: 40px 30px 30px;
.login_title {
margin-bottom: $margin-text;
font-size: $font-size-title-2;
color: $color-text-1;
}
.login_title_desc {
font-size: $font-size-body-1;
color: $color-text-3;
}
.author {
position: absolute;
bottom: 30px;
font-size: $font-size-body-1;
color: $color-text-4;
}
}
}
}
</style>
+64 -64
View File
@@ -1,64 +1,64 @@
interface List {
id: number;
order_id: string;
trade_id: string;
trade_type: string;
rate: string;
amount: string;
money: number;
address: string;
from_address: string;
status: number;
name: string;
api_type: string;
return_url: string;
notify_url: string;
notify_num: number;
notify_state: number;
ref_hash: string;
ref_block_num: number;
expired_at: string;
confirmed_at?: string;
created_at?: string;
updated_at?: string;
}
interface FormData {
form: {
order_id: string;
trade_id: string;
trade_type: string;
address: string;
status?: number;
createTime: string[];
};
search: boolean;
}
interface AddForm {
name: string;
address: string;
trade_type: string;
remark: string;
other_notify: number;
}
interface ModForm {
id: number;
name: string;
status: number;
address: string;
trade_type: string;
remark: string;
other_notify: number;
}
interface Pagination {
showPageSize: boolean;
showTotal: boolean;
current: number;
pageSize: number;
total: number;
}
export type { List, FormData, Pagination, AddForm, ModForm };
interface List {
id: number;
order_id: string;
trade_id: string;
trade_type: string;
rate: string;
amount: string;
money: number;
address: string;
from_address: string;
status: number;
name: string;
api_type: string;
return_url: string;
notify_url: string;
notify_num: number;
notify_state: number;
ref_hash: string;
ref_block_num: number;
expired_at: string;
confirmed_at?: string;
created_at?: string;
updated_at?: string;
}
interface FormData {
form: {
order_id: string;
trade_id: string;
trade_type: string;
address: string;
status?: number;
createTime: string[];
};
search: boolean;
}
interface AddForm {
name: string;
address: string;
trade_type: string;
remark: string;
other_notify: number;
}
interface ModForm {
id: number;
name: string;
status: number;
address: string;
trade_type: string;
remark: string;
other_notify: number;
}
interface Pagination {
showPageSize: boolean;
showTotal: boolean;
current: number;
pageSize: number;
total: number;
}
export type { List, FormData, Pagination, AddForm, ModForm };
+433 -433
View File
@@ -1,433 +1,433 @@
<template>
<div class="snow-page">
<div class="snow-inner">
<a-form ref="formRef" auto-label-width :model="formData.form">
<a-row :gutter="16">
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="order_id" label="商户订单">
<a-input v-model="formData.form.order_id" placeholder="请输入商户订单" allow-clear />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="trade_type" label="交易类型">
<a-select v-model="formData.form.trade_type" placeholder="请选择交易类型" allow-clear allow-search>
<a-option v-for="item in tradeTypeOptions" :key="item.value" :value="item.value">
{{ item.label }}
</a-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="status" label="订单状态">
<a-select v-model="formData.form.status" placeholder="请选择订单状态" allow-clear>
<a-option v-for="item in statusOptions" :key="item.value" :value="item.value">
{{ item.label }}
</a-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-space class="search-btn" wrap>
<a-button type="primary" @click="getOrderList">
<template #icon><icon-search /></template>
查询
</a-button>
<a-button @click="onReset">
<template #icon><icon-refresh /></template>
重置
</a-button>
<a-popconfirm :content="batchDelConfirm" type="warning" @ok="onBatchDelete">
<a-button v-show="selectedKeys.length > 0" type="primary" status="danger">
<template #icon><icon-delete /></template>
删除
</a-button>
</a-popconfirm>
<a-button type="text" @click="formData.search = !formData.search">
{{ formData.search ? "收起" : "展开" }}
<icon-down :class="{ 'rotate-icon': formData.search }" />
</a-button>
</a-space>
</a-col>
</a-row>
<a-row :gutter="16" v-if="formData.search">
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="trade_id" label="交易ID">
<a-input v-model="formData.form.trade_id" placeholder="请输入交易ID" allow-clear />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="address" label="钱包地址">
<a-input v-model="formData.form.address" placeholder="请输入钱包地址" allow-clear />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="createTime" label="创建时间">
<a-range-picker v-model="formData.form.createTime" show-time format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
</a-form-item>
</a-col>
</a-row>
</a-form>
<a-table
row-key="id"
size="small"
:bordered="{ cell: true }"
:scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
:loading="loading"
:columns="columns"
:data="data"
v-model:selectedKeys="selectedKeys"
:row-selection="orderSelection"
:pagination="pagination"
@page-change="pageChange"
@page-size-change="pageSizeChange"
>
<template #wallet="{ record }">
<a-tooltip :content="record.address" position="top">
<span class="wallet-name">
{{ record.wallet?.name || record.channel?.name || (record.address ? `${record.address.slice(-8)}` : "--") }}
</span>
</a-tooltip>
</template>
<template #amount="{ record }">
<span>
{{ record.amount }}
<a-tag size="mini" :color="getCryptoColor(record.crypto)" bordered style="margin-left: 4px">{{
record.crypto
}}</a-tag>
</span>
</template>
<template #money="{ record }">
<span>
{{ record.money }}
<a-tag size="mini" color="arcoblue" style="margin-left: 4px">{{ record.fiat }}</a-tag>
</span>
</template>
<template #status="{ record }">
<a-tag size="small" :color="getStatusColor(record.status)">
{{ getStatusText(record.status) }}
</a-tag>
</template>
<template #notify_state="{ record }">
<a-tag size="small" :color="record.status === 2 ? (record.notify_state === 1 ? 'blue' : 'red') : 'gray'">
{{ record.status === 2 ? (record.notify_state === 1 ? "成功" : "失败") : "-" }}
</a-tag>
</template>
<!-- 不常用的操作优先放置在详情页,尽量保持第一视角的干净整洁 -->
<template #optional="{ record }">
<a-space wrap>
<a-button size="mini" type="primary" @click="showDetail(record)">详情</a-button>
<a-button size="mini" type="primary" status="warning" :disabled="record.status === 2" @click="showPaidModal(record)">
补单
</a-button>
</a-space>
</template>
</a-table>
</div>
</div>
<DetailModal :visible="detailVisible" :detailData="detailData" @close="closeDetail" />
<!-- 补单弹窗 -->
<a-modal
v-model:visible="paidModalVisible"
title="确认补单操作"
@ok="confirmPaid"
@cancel="closePaidModal"
ok-text="确认补单"
cancel-text="取消"
:width="paidDialogWidth"
:mask-closable="false"
>
<div class="paid-modal-content">
<a-alert type="warning" style="margin-bottom: 20px">
<template #icon>
<icon-exclamation-circle-fill />
</template>
<div style="font-weight: 500">注意</div>
<div style="font-size: 13px; margin-top: 4px; color: #666">
补单操作将强制标记订单为已支付,即使用户实际未付款、谨慎操作!
</div>
</a-alert>
<a-form :model="paidForm" layout="vertical">
<a-form-item field="ref_hash" label="交易哈希" :rules="[{ maxLength: 200, message: '哈希值不能超过200个字符' }]">
<a-input v-model="paidForm.ref_hash" placeholder="请输入区块链交易哈希值(可选)" allow-clear>
<template #prefix>
<icon-link />
</template>
</a-input>
<template #extra>
<div style="font-size: 12px; color: #86909c; margin-top: 4px">如有实际交易,建议填写对应的区块链交易哈希值</div>
</template>
</a-form-item>
</a-form>
</div>
</a-modal>
</template>
<script setup lang="ts">
import { listAPI, paidAPI, delOrderApi } from "@/api/modules/order/index";
import { List, FormData, Pagination } from "./config";
import { Notification } from "@arco-design/web-vue";
import { useUserInfoStore } from "@/store/modules/user-info";
import DetailModal from "./components/detail.vue";
import { useOrderDetail } from "./detail";
import { getCryptoColor } from "@/views/rate/common";
import { useLayoutModel } from "@/hooks/useLayoutModel";
const userStores = useUserInfoStore();
const { detailVisible, detailData, showDetail, closeDetail } = useOrderDetail();
const { dialogWidth } = useLayoutModel();
const paidDialogWidth = computed(() => dialogWidth("500px"));
const tradeTypeOptions = computed(() => Object.entries(userStores.trade_type).map(([value, label]) => ({ value, label })));
const statusOptions = [
{ value: 1, label: "等待支付" },
{ value: 2, label: "支付成功" },
{ value: 3, label: "交易过期" },
{ value: 4, label: "交易取消" },
{ value: 5, label: "等待确认" },
{ value: 6, label: "确认失败" }
];
const formData = reactive<FormData>({
form: {
order_id: "",
trade_id: "",
trade_type: "",
address: "",
status: undefined,
createTime: []
},
search: false
});
const selectedKeys = ref<string[]>([]);
const orderSelection = reactive({
type: "checkbox",
showCheckedAll: true,
onlyCurrent: false
});
const batchDelConfirm = computed(() => `确定删除这${selectedKeys.value.length}条数据吗?`);
const loading = ref(false);
const data = reactive<List[]>([]);
const pagination = ref<Pagination>({
showPageSize: true,
showTotal: true,
current: 1,
pageSize: 10,
total: 10
});
const columns = [
{ title: "ID", align: "center", dataIndex: "id", width: 80 },
{ title: "商户订单", align: "center", dataIndex: "order_id", width: 220, ellipsis: true, tooltip: true },
{ title: "交易类型", align: "center", dataIndex: "trade_type", width: 120 },
{ title: "交易数额", align: "center", dataIndex: "amount", slotName: "amount", width: 150 },
{ title: "交易金额", align: "center", dataIndex: "money", slotName: "money", width: 150 },
{ title: "收款钱包", align: "center", dataIndex: "wallet.name", slotName: "wallet", width: 150, ellipsis: true },
{ title: "交易状态", dataIndex: "status", align: "center", slotName: "status", width: 100 },
{ title: "回调", dataIndex: "notify_state", align: "center", slotName: "notify_state", width: 80 },
{ title: "创建时间", dataIndex: "created_at", align: "center", width: 160 },
{ title: "操作", slotName: "optional", align: "center", fixed: "right", width: 150 }
];
const statusMap: Record<number, { color: string; text: string }> = {
1: { color: "blue", text: "等待支付" },
2: { color: "green", text: "交易成功" },
3: { color: "gray", text: "交易过期" },
4: { color: "gold", text: "交易取消" },
5: { color: "pinkpurple", text: "等待确认" },
6: { color: "red", text: "确认失败" }
};
const getStatusColor = (status: number): string => statusMap[status]?.color || "gray";
const getStatusText = (status: number): string => statusMap[status]?.text || "未知";
const pageChange = (page: number) => {
pagination.value.current = page;
getOrderList();
};
const pageSizeChange = (pageSize: number) => {
pagination.value.pageSize = pageSize;
getOrderList();
};
const onReset = () => {
formData.form = {
order_id: "",
trade_id: "",
trade_type: "",
address: "",
status: undefined,
createTime: []
};
getOrderList();
};
const getOrderList = async () => {
try {
loading.value = true;
const params: any = {
page: pagination.value.current,
size: pagination.value.pageSize,
sort: "desc",
keyword: "",
order_id: formData.form.order_id,
trade_id: formData.form.trade_id,
address: formData.form.address,
trade_type: formData.form.trade_type
};
// 添加状态筛选
if (formData.form.status !== undefined) {
params.status = formData.form.status;
}
// 添加时间范围筛选
if (formData.form.createTime && formData.form.createTime.length === 2) {
params.start_at = formData.form.createTime[0];
params.end_at = formData.form.createTime[1];
}
const res = await listAPI(params);
data.length = 0;
data.push(...res.data);
pagination.value.total = res.total;
} finally {
loading.value = false;
}
};
const paidModalVisible = ref(false);
const paidForm = reactive({
ref_hash: "",
recordId: 0
});
const showPaidModal = (record: List) => {
paidForm.recordId = record.id;
paidForm.ref_hash = "";
paidModalVisible.value = true;
};
const closePaidModal = () => {
paidModalVisible.value = false;
paidForm.ref_hash = "";
paidForm.recordId = 0;
};
const confirmPaid = async () => {
try {
await paidAPI({
id: paidForm.recordId,
ref_hash: paidForm.ref_hash || "" // 确保空时传递空字符串
});
closePaidModal();
getOrderList();
Notification.success("补单成功");
} catch (error) {
Notification.error(error);
}
};
const onBatchDelete = async () => {
try {
await delOrderApi({ ids: selectedKeys.value });
pagination.value.current = 1;
getOrderList();
Notification.success("删除成功");
selectedKeys.value = [];
} catch (error) {
Notification.error(error);
}
};
getOrderList();
</script>
<style lang="scss" scoped>
.rotate-icon {
transform: rotate(180deg);
transition: transform 0.3s;
}
.search-btn {
margin-bottom: 20px;
}
.wallet-name {
cursor: help;
color: $color-link;
&:hover {
text-decoration: underline;
}
}
// 在 style 标签中添加
.paid-modal-content {
padding: 4px 0;
:deep(.arco-alert) {
border-radius: 6px;
}
:deep(.arco-form-item-label-col) {
font-weight: 500;
color: $color-text-1;
}
:deep(.arco-input-wrapper) {
&:hover {
border-color: $color-primary;
}
}
}
:deep(.arco-modal) {
.arco-modal-header {
border-bottom: 1px solid var(--color-neutral-3);
padding: 16px 20px;
}
.arco-modal-body {
padding: 20px;
}
.arco-modal-footer {
border-top: 1px solid var(--color-neutral-3);
padding: 12px 20px;
}
}
// 响应式处理
@media (max-width: 1200px) {
:deep(.arco-table-th),
:deep(.arco-table-td) {
padding: 8px 6px !important;
font-size: 12px;
}
}
@media (max-width: 768px) {
:deep(.arco-modal) {
width: 95vw !important;
margin: 10px;
}
:deep(.arco-table-th),
:deep(.arco-table-td) {
padding: 6px 4px !important;
font-size: 11px;
}
}
</style>
<template>
<div class="snow-page">
<div class="snow-inner">
<a-form ref="formRef" auto-label-width :model="formData.form">
<a-row :gutter="16">
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="order_id" label="商户订单">
<a-input v-model="formData.form.order_id" placeholder="请输入商户订单" allow-clear />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="trade_type" label="交易类型">
<a-select v-model="formData.form.trade_type" placeholder="请选择交易类型" allow-clear allow-search>
<a-option v-for="item in tradeTypeOptions" :key="item.value" :value="item.value">
{{ item.label }}
</a-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="status" label="订单状态">
<a-select v-model="formData.form.status" placeholder="请选择订单状态" allow-clear>
<a-option v-for="item in statusOptions" :key="item.value" :value="item.value">
{{ item.label }}
</a-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-space class="search-btn" wrap>
<a-button type="primary" @click="getOrderList">
<template #icon><icon-search /></template>
查询
</a-button>
<a-button @click="onReset">
<template #icon><icon-refresh /></template>
重置
</a-button>
<a-popconfirm :content="batchDelConfirm" type="warning" @ok="onBatchDelete">
<a-button v-show="selectedKeys.length > 0" type="primary" status="danger">
<template #icon><icon-delete /></template>
删除
</a-button>
</a-popconfirm>
<a-button type="text" @click="formData.search = !formData.search">
{{ formData.search ? "收起" : "展开" }}
<icon-down :class="{ 'rotate-icon': formData.search }" />
</a-button>
</a-space>
</a-col>
</a-row>
<a-row :gutter="16" v-if="formData.search">
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="trade_id" label="交易ID">
<a-input v-model="formData.form.trade_id" placeholder="请输入交易ID" allow-clear />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="address" label="钱包地址">
<a-input v-model="formData.form.address" placeholder="请输入钱包地址" allow-clear />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="createTime" label="创建时间">
<a-range-picker v-model="formData.form.createTime" show-time format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
</a-form-item>
</a-col>
</a-row>
</a-form>
<a-table
row-key="id"
size="small"
:bordered="{ cell: true }"
:scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
:loading="loading"
:columns="columns"
:data="data"
v-model:selectedKeys="selectedKeys"
:row-selection="orderSelection"
:pagination="pagination"
@page-change="pageChange"
@page-size-change="pageSizeChange"
>
<template #wallet="{ record }">
<a-tooltip :content="record.address" position="top">
<span class="wallet-name">
{{ record.wallet?.name || record.channel?.name || (record.address ? `${record.address.slice(-8)}` : "--") }}
</span>
</a-tooltip>
</template>
<template #amount="{ record }">
<span>
{{ record.amount }}
<a-tag size="mini" :color="getCryptoColor(record.crypto)" bordered style="margin-left: 4px">{{
record.crypto
}}</a-tag>
</span>
</template>
<template #money="{ record }">
<span>
{{ record.money }}
<a-tag size="mini" color="arcoblue" style="margin-left: 4px">{{ record.fiat }}</a-tag>
</span>
</template>
<template #status="{ record }">
<a-tag size="small" :color="getStatusColor(record.status)">
{{ getStatusText(record.status) }}
</a-tag>
</template>
<template #notify_state="{ record }">
<a-tag size="small" :color="record.status === 2 ? (record.notify_state === 1 ? 'blue' : 'red') : 'gray'">
{{ record.status === 2 ? (record.notify_state === 1 ? "成功" : "失败") : "-" }}
</a-tag>
</template>
<!-- 不常用的操作优先放置在详情页,尽量保持第一视角的干净整洁 -->
<template #optional="{ record }">
<a-space wrap>
<a-button size="mini" type="primary" @click="showDetail(record)">详情</a-button>
<a-button size="mini" type="primary" status="warning" :disabled="record.status === 2" @click="showPaidModal(record)">
补单
</a-button>
</a-space>
</template>
</a-table>
</div>
</div>
<DetailModal :visible="detailVisible" :detailData="detailData" @close="closeDetail" />
<!-- 补单弹窗 -->
<a-modal
v-model:visible="paidModalVisible"
title="确认补单操作"
@ok="confirmPaid"
@cancel="closePaidModal"
ok-text="确认补单"
cancel-text="取消"
:width="paidDialogWidth"
:mask-closable="false"
>
<div class="paid-modal-content">
<a-alert type="warning" style="margin-bottom: 20px">
<template #icon>
<icon-exclamation-circle-fill />
</template>
<div style="font-weight: 500">注意</div>
<div style="font-size: 13px; margin-top: 4px; color: #666">
补单操作将强制标记订单为已支付,即使用户实际未付款、谨慎操作!
</div>
</a-alert>
<a-form :model="paidForm" layout="vertical">
<a-form-item field="ref_hash" label="交易哈希" :rules="[{ maxLength: 200, message: '哈希值不能超过200个字符' }]">
<a-input v-model="paidForm.ref_hash" placeholder="请输入区块链交易哈希值(可选)" allow-clear>
<template #prefix>
<icon-link />
</template>
</a-input>
<template #extra>
<div style="font-size: 12px; color: #86909c; margin-top: 4px">如有实际交易,建议填写对应的区块链交易哈希值</div>
</template>
</a-form-item>
</a-form>
</div>
</a-modal>
</template>
<script setup lang="ts">
import { listAPI, paidAPI, delOrderApi } from "@/api/modules/order/index";
import { List, FormData, Pagination } from "./config";
import { Notification } from "@arco-design/web-vue";
import { useUserInfoStore } from "@/store/modules/user-info";
import DetailModal from "./components/detail.vue";
import { useOrderDetail } from "./detail";
import { getCryptoColor } from "@/views/rate/common";
import { useLayoutModel } from "@/hooks/useLayoutModel";
const userStores = useUserInfoStore();
const { detailVisible, detailData, showDetail, closeDetail } = useOrderDetail();
const { dialogWidth } = useLayoutModel();
const paidDialogWidth = computed(() => dialogWidth("500px"));
const tradeTypeOptions = computed(() => Object.entries(userStores.trade_type).map(([value, label]) => ({ value, label })));
const statusOptions = [
{ value: 1, label: "等待支付" },
{ value: 2, label: "支付成功" },
{ value: 3, label: "交易过期" },
{ value: 4, label: "交易取消" },
{ value: 5, label: "等待确认" },
{ value: 6, label: "确认失败" }
];
const formData = reactive<FormData>({
form: {
order_id: "",
trade_id: "",
trade_type: "",
address: "",
status: undefined,
createTime: []
},
search: false
});
const selectedKeys = ref<string[]>([]);
const orderSelection = reactive({
type: "checkbox",
showCheckedAll: true,
onlyCurrent: false
});
const batchDelConfirm = computed(() => `确定删除这${selectedKeys.value.length}条数据吗?`);
const loading = ref(false);
const data = reactive<List[]>([]);
const pagination = ref<Pagination>({
showPageSize: true,
showTotal: true,
current: 1,
pageSize: 10,
total: 10
});
const columns = [
{ title: "ID", align: "center", dataIndex: "id", width: 80 },
{ title: "商户订单", align: "center", dataIndex: "order_id", width: 220, ellipsis: true, tooltip: true },
{ title: "交易类型", align: "center", dataIndex: "trade_type", width: 120 },
{ title: "交易数额", align: "center", dataIndex: "amount", slotName: "amount", width: 150 },
{ title: "交易金额", align: "center", dataIndex: "money", slotName: "money", width: 150 },
{ title: "收款钱包", align: "center", dataIndex: "wallet.name", slotName: "wallet", width: 150, ellipsis: true },
{ title: "交易状态", dataIndex: "status", align: "center", slotName: "status", width: 100 },
{ title: "回调", dataIndex: "notify_state", align: "center", slotName: "notify_state", width: 80 },
{ title: "创建时间", dataIndex: "created_at", align: "center", width: 160 },
{ title: "操作", slotName: "optional", align: "center", fixed: "right", width: 150 }
];
const statusMap: Record<number, { color: string; text: string }> = {
1: { color: "blue", text: "等待支付" },
2: { color: "green", text: "交易成功" },
3: { color: "gray", text: "交易过期" },
4: { color: "gold", text: "交易取消" },
5: { color: "pinkpurple", text: "等待确认" },
6: { color: "red", text: "确认失败" }
};
const getStatusColor = (status: number): string => statusMap[status]?.color || "gray";
const getStatusText = (status: number): string => statusMap[status]?.text || "未知";
const pageChange = (page: number) => {
pagination.value.current = page;
getOrderList();
};
const pageSizeChange = (pageSize: number) => {
pagination.value.pageSize = pageSize;
getOrderList();
};
const onReset = () => {
formData.form = {
order_id: "",
trade_id: "",
trade_type: "",
address: "",
status: undefined,
createTime: []
};
getOrderList();
};
const getOrderList = async () => {
try {
loading.value = true;
const params: any = {
page: pagination.value.current,
size: pagination.value.pageSize,
sort: "desc",
keyword: "",
order_id: formData.form.order_id,
trade_id: formData.form.trade_id,
address: formData.form.address,
trade_type: formData.form.trade_type
};
// 添加状态筛选
if (formData.form.status !== undefined) {
params.status = formData.form.status;
}
// 添加时间范围筛选
if (formData.form.createTime && formData.form.createTime.length === 2) {
params.start_at = formData.form.createTime[0];
params.end_at = formData.form.createTime[1];
}
const res = await listAPI(params);
data.length = 0;
data.push(...res.data);
pagination.value.total = res.total;
} finally {
loading.value = false;
}
};
const paidModalVisible = ref(false);
const paidForm = reactive({
ref_hash: "",
recordId: 0
});
const showPaidModal = (record: List) => {
paidForm.recordId = record.id;
paidForm.ref_hash = "";
paidModalVisible.value = true;
};
const closePaidModal = () => {
paidModalVisible.value = false;
paidForm.ref_hash = "";
paidForm.recordId = 0;
};
const confirmPaid = async () => {
try {
await paidAPI({
id: paidForm.recordId,
ref_hash: paidForm.ref_hash || "" // 确保空时传递空字符串
});
closePaidModal();
getOrderList();
Notification.success("补单成功");
} catch (error) {
Notification.error(error);
}
};
const onBatchDelete = async () => {
try {
await delOrderApi({ ids: selectedKeys.value });
pagination.value.current = 1;
getOrderList();
Notification.success("删除成功");
selectedKeys.value = [];
} catch (error) {
Notification.error(error);
}
};
getOrderList();
</script>
<style lang="scss" scoped>
.rotate-icon {
transform: rotate(180deg);
transition: transform 0.3s;
}
.search-btn {
margin-bottom: 20px;
}
.wallet-name {
cursor: help;
color: $color-link;
&:hover {
text-decoration: underline;
}
}
// 在 style 标签中添加
.paid-modal-content {
padding: 4px 0;
:deep(.arco-alert) {
border-radius: 6px;
}
:deep(.arco-form-item-label-col) {
font-weight: 500;
color: $color-text-1;
}
:deep(.arco-input-wrapper) {
&:hover {
border-color: $color-primary;
}
}
}
:deep(.arco-modal) {
.arco-modal-header {
border-bottom: 1px solid var(--color-neutral-3);
padding: 16px 20px;
}
.arco-modal-body {
padding: 20px;
}
.arco-modal-footer {
border-top: 1px solid var(--color-neutral-3);
padding: 12px 20px;
}
}
// 响应式处理
@media (max-width: 1200px) {
:deep(.arco-table-th),
:deep(.arco-table-td) {
padding: 8px 6px !important;
font-size: 12px;
}
}
@media (max-width: 768px) {
:deep(.arco-modal) {
width: 95vw !important;
margin: 10px;
}
:deep(.arco-table-th),
:deep(.arco-table-td) {
padding: 6px 4px !important;
font-size: 11px;
}
}
</style>
+46 -46
View File
@@ -1,46 +1,46 @@
interface List {
id: number;
fiat: string;
crypto: string;
rate: number;
raw_rate: number;
created_at: string;
key?: string;
}
interface FormData {
form: {
fiat: string;
crypto: string;
datetime: string[];
};
search: boolean;
}
interface AddForm {
name: string;
address: string;
trade_type: string;
remark: string;
other_notify: number;
}
interface ModForm {
id: number;
name: string;
status: number;
address: string;
trade_type: string;
remark: string;
other_notify: number;
}
interface Pagination {
showPageSize: boolean;
showTotal: boolean;
current: number;
pageSize: number;
total: number;
}
export type { List, FormData, Pagination, AddForm, ModForm };
interface List {
id: number;
fiat: string;
crypto: string;
rate: number;
raw_rate: number;
created_at: string;
key?: string;
}
interface FormData {
form: {
fiat: string;
crypto: string;
datetime: string[];
};
search: boolean;
}
interface AddForm {
name: string;
address: string;
trade_type: string;
remark: string;
other_notify: number;
}
interface ModForm {
id: number;
name: string;
status: number;
address: string;
trade_type: string;
remark: string;
other_notify: number;
}
interface Pagination {
showPageSize: boolean;
showTotal: boolean;
current: number;
pageSize: number;
total: number;
}
export type { List, FormData, Pagination, AddForm, ModForm };
+184 -184
View File
@@ -1,184 +1,184 @@
<template>
<div class="snow-page">
<div class="snow-inner">
<a-form ref="formRef" auto-label-width :model="formData.form">
<a-row :gutter="16">
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="fiat" label="交易法币">
<a-select v-model="formData.form.fiat" placeholder="请选择交易法币" allow-clear allow-search>
<a-option v-for="item in tradeFiatOptions" :key="item.value" :value="item.value">
{{ item.value }}
</a-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="crypto" label="加密货币">
<a-select v-model="formData.form.crypto" placeholder="请选择加密货币" allow-clear allow-search>
<a-option v-for="item in tradeCryptoOptions" :key="item.value" :value="item.value">
{{ item.value }}
</a-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="datetime" label="同步时间">
<a-range-picker
v-model="formData.form.datetime"
:placeholder="['开始时间', '结束时间']"
show-time
format="YYYY-MM-DD HH:mm"
style="width: 100%"
allow-clear
/>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-space class="search-btn" wrap>
<a-button type="primary" @click="getCommonTableList">
<template #icon><icon-search /></template>
查询
</a-button>
<a-button @click="onReset">
<template #icon><icon-refresh /></template>
重置
</a-button>
<a-button type="primary" status="success" @click="onSync">
<template #icon><icon-loop /></template>
立刻同步
</a-button>
</a-space>
</a-col>
</a-row>
</a-form>
<a-divider :margin="10" />
<a-table
row-key="key"
size="medium"
:bordered="{ cell: true }"
:scroll="{ x: 510, y: 600 }"
:loading="loading"
:columns="columns"
:data="data"
v-model:selectedKeys="selectedKeys"
:pagination="pagination"
@page-change="pageChange"
@page-size-change="pageSizeChange"
>
<template #fiat="{ record }">
<span class="fiat-display">
{{ getFiatFlag(record.fiat) }} <strong>{{ record.fiat }}</strong>
</span>
</template>
<template #crypto="{ record }">
<a-tag :color="getCryptoColor(record.crypto)" bordered>
{{ record.crypto }}
</a-tag>
</template>
</a-table>
</div>
</div>
</template>
<script setup lang="ts">
import { getRateListAPI, onSyncAPI } from "@/api/modules/rate/index";
import { List, FormData, Pagination } from "./list";
import { useUserInfoStore } from "@/store/modules/user-info";
import { getFiatFlag, getCryptoColor } from "@/views/rate/common";
import { Message } from "@arco-design/web-vue";
const userStores = useUserInfoStore();
const tradeCryptoOptions = computed(() =>
Object.keys(userStores.trade_crypto ?? {}).map((crypto: string) => ({ value: crypto, label: crypto }))
);
const tradeFiatOptions = computed(() =>
Object.keys(userStores.trade_fiat ?? {}).map((fiat: string) => ({ value: fiat, label: fiat }))
);
const formData = reactive<FormData>({
form: { fiat: "", crypto: "", datetime: [] },
search: false
});
const selectedKeys = ref<string[]>([]);
const pagination = ref<Pagination>({
showPageSize: true,
showTotal: true,
current: 1,
pageSize: 10,
total: 10
});
const loading = ref(false);
const data = reactive<List[]>([]);
const columns = [
{ title: "交易法币", align: "center", dataIndex: "fiat", width: 102, slotName: "fiat" },
{ title: "加密货币", align: "center", dataIndex: "crypto", width: 92, slotName: "crypto" },
{ title: "订单汇率", align: "center", dataIndex: "rate", width: 102 },
{ title: "基准汇率", dataIndex: "raw_rate", align: "center", slotName: "raw_rate", width: 102 },
{ title: "同步时间", dataIndex: "created_at", align: "center", slotName: "created_at", width: 212 }
];
const getCommonTableList = async () => {
try {
loading.value = true;
const res = await getRateListAPI({
page: pagination.value.current,
size: pagination.value.pageSize,
sort: "desc",
keyword: "",
fiat: formData.form.fiat,
crypto: formData.form.crypto,
datetime: formData.form.datetime,
status: 99
});
data.length = 0;
data.push(...res.data);
pagination.value.total = res.total;
} finally {
loading.value = false;
}
};
const onSync = async () => {
try {
await onSyncAPI({});
Message.success("同步成功!");
getCommonTableList();
} catch (error) {
console.error("同步失败:", error);
Message.error("同步失败,请重试");
}
};
const onReset = () => {
formData.form = { fiat: "", crypto: "", datetime: [] };
getCommonTableList();
};
const pageChange = (page: number) => {
pagination.value.current = page;
getCommonTableList();
};
const pageSizeChange = (pageSize: number) => {
pagination.value.pageSize = pageSize;
getCommonTableList();
};
getCommonTableList();
</script>
<style lang="scss" scoped>
.search-btn {
margin-bottom: 20px;
}
.fiat-display {
display: inline-flex;
align-items: center;
gap: 4px;
}
</style>
<template>
<div class="snow-page">
<div class="snow-inner">
<a-form ref="formRef" auto-label-width :model="formData.form">
<a-row :gutter="16">
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="fiat" label="交易法币">
<a-select v-model="formData.form.fiat" placeholder="请选择交易法币" allow-clear allow-search>
<a-option v-for="item in tradeFiatOptions" :key="item.value" :value="item.value">
{{ item.value }}
</a-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="crypto" label="加密货币">
<a-select v-model="formData.form.crypto" placeholder="请选择加密货币" allow-clear allow-search>
<a-option v-for="item in tradeCryptoOptions" :key="item.value" :value="item.value">
{{ item.value }}
</a-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-form-item field="datetime" label="同步时间">
<a-range-picker
v-model="formData.form.datetime"
:placeholder="['开始时间', '结束时间']"
show-time
format="YYYY-MM-DD HH:mm"
style="width: 100%"
allow-clear
/>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6" :xxl="6">
<a-space class="search-btn" wrap>
<a-button type="primary" @click="getCommonTableList">
<template #icon><icon-search /></template>
查询
</a-button>
<a-button @click="onReset">
<template #icon><icon-refresh /></template>
重置
</a-button>
<a-button type="primary" status="success" @click="onSync">
<template #icon><icon-loop /></template>
立刻同步
</a-button>
</a-space>
</a-col>
</a-row>
</a-form>
<a-divider :margin="10" />
<a-table
row-key="key"
size="medium"
:bordered="{ cell: true }"
:scroll="{ x: 510, y: 600 }"
:loading="loading"
:columns="columns"
:data="data"
v-model:selectedKeys="selectedKeys"
:pagination="pagination"
@page-change="pageChange"
@page-size-change="pageSizeChange"
>
<template #fiat="{ record }">
<span class="fiat-display">
{{ getFiatFlag(record.fiat) }} <strong>{{ record.fiat }}</strong>
</span>
</template>
<template #crypto="{ record }">
<a-tag :color="getCryptoColor(record.crypto)" bordered>
{{ record.crypto }}
</a-tag>
</template>
</a-table>
</div>
</div>
</template>
<script setup lang="ts">
import { getRateListAPI, onSyncAPI } from "@/api/modules/rate/index";
import { List, FormData, Pagination } from "./list";
import { useUserInfoStore } from "@/store/modules/user-info";
import { getFiatFlag, getCryptoColor } from "@/views/rate/common";
import { Message } from "@arco-design/web-vue";
const userStores = useUserInfoStore();
const tradeCryptoOptions = computed(() =>
Object.keys(userStores.trade_crypto ?? {}).map((crypto: string) => ({ value: crypto, label: crypto }))
);
const tradeFiatOptions = computed(() =>
Object.keys(userStores.trade_fiat ?? {}).map((fiat: string) => ({ value: fiat, label: fiat }))
);
const formData = reactive<FormData>({
form: { fiat: "", crypto: "", datetime: [] },
search: false
});
const selectedKeys = ref<string[]>([]);
const pagination = ref<Pagination>({
showPageSize: true,
showTotal: true,
current: 1,
pageSize: 10,
total: 10
});
const loading = ref(false);
const data = reactive<List[]>([]);
const columns = [
{ title: "交易法币", align: "center", dataIndex: "fiat", width: 102, slotName: "fiat" },
{ title: "加密货币", align: "center", dataIndex: "crypto", width: 92, slotName: "crypto" },
{ title: "订单汇率", align: "center", dataIndex: "rate", width: 102 },
{ title: "基准汇率", dataIndex: "raw_rate", align: "center", slotName: "raw_rate", width: 102 },
{ title: "同步时间", dataIndex: "created_at", align: "center", slotName: "created_at", width: 212 }
];
const getCommonTableList = async () => {
try {
loading.value = true;
const res = await getRateListAPI({
page: pagination.value.current,
size: pagination.value.pageSize,
sort: "desc",
keyword: "",
fiat: formData.form.fiat,
crypto: formData.form.crypto,
datetime: formData.form.datetime,
status: 99
});
data.length = 0;
data.push(...res.data);
pagination.value.total = res.total;
} finally {
loading.value = false;
}
};
const onSync = async () => {
try {
await onSyncAPI({});
Message.success("同步成功!");
getCommonTableList();
} catch (error) {
console.error("同步失败:", error);
Message.error("同步失败,请重试");
}
};
const onReset = () => {
formData.form = { fiat: "", crypto: "", datetime: [] };
getCommonTableList();
};
const pageChange = (page: number) => {
pagination.value.current = page;
getCommonTableList();
};
const pageSizeChange = (pageSize: number) => {
pagination.value.pageSize = pageSize;
getCommonTableList();
};
getCommonTableList();
</script>
<style lang="scss" scoped>
.search-btn {
margin-bottom: 20px;
}
.fiat-display {
display: inline-flex;
align-items: center;
gap: 4px;
}
</style>
+12 -12
View File
@@ -1,12 +1,12 @@
interface List {
key: string;
fiat: string;
crypto: string;
syntax: string;
}
interface EditForm {
fiat: string;
crypto: string;
syntax: string;
}
export type { List, EditForm };
interface List {
key: string;
fiat: string;
crypto: string;
syntax: string;
}
interface EditForm {
fiat: string;
crypto: string;
syntax: string;
}
export type { List, EditForm };
File diff suppressed because it is too large Load Diff

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