From cb91140ab8a8562bf95e58bbaa75c435b903781c Mon Sep 17 00:00:00 2001 From: xiangshu233 Date: Sat, 17 Feb 2024 13:52:03 +0800 Subject: [PATCH] style: :lipstick: eslint --fix --- build/constant.ts | 4 +- build/getConfigFileName.ts | 6 +- build/script/buildConf.ts | 37 ++-- build/script/postBuild.ts | 25 +-- build/utils.ts | 52 +++--- build/vite/plugin/compress.ts | 20 +-- build/vite/plugin/html.ts | 20 +-- build/vite/plugin/index.ts | 40 ++--- build/vite/plugin/mock.ts | 4 +- build/vite/plugin/svgSprite.ts | 8 +- build/vite/plugin/visualizer.ts | 10 +- build/vite/proxy.ts | 22 +-- commitlint.config.cjs | 22 +-- index.html | 55 +++--- mock/_createProductionServer.ts | 14 +- mock/_util.ts | 42 ++--- mock/user/user.ts | 49 ++--- postcss.config.cjs => postcss.config.js | 14 +- src/App.vue | 108 +++++------ src/api/system/user.ts | 20 +-- src/components/SvgIcon.vue | 73 ++++---- src/enums/breakpointEnum.ts | 16 +- src/enums/cacheEnum.ts | 10 +- src/enums/pageEnum.ts | 1 + src/hooks/core/useTimeout.ts | 43 ++--- src/hooks/event/useBreakpoint.ts | 92 +++++----- src/hooks/event/useEventListener.ts | 61 ++++--- src/hooks/event/useWindowSizeFn.ts | 37 ++-- src/hooks/index.ts | 4 +- src/hooks/setting/index.ts | 20 +-- src/hooks/setting/useDesignSetting.ts | 18 +- src/hooks/use-async.ts | 19 +- src/hooks/useDomWidth.ts | 18 +- src/hooks/useOnline.ts | 26 +-- src/hooks/useTime.ts | 58 +++--- src/hooks/web/useECharts.ts | 113 ++++++------ src/layout/index.vue | 44 ++--- src/main.ts | 40 ++--- src/router/base.ts | 12 +- src/router/index.ts | 29 +-- src/router/modules.ts | 8 +- src/router/router-guards.ts | 75 ++++---- src/settings/animateSetting.ts | 2 +- src/settings/componentSetting.ts | 8 +- src/settings/designSetting.ts | 26 +-- src/store/index.ts | 14 +- src/store/modules/designSetting.ts | 28 +-- src/store/modules/route.ts | 24 +-- src/store/modules/user.ts | 111 ++++++------ src/store/mutation-types.ts | 8 +- src/styles/common.less | 6 +- src/styles/transition/fade.less | 8 +- src/styles/transition/index.less | 5 +- src/styles/transition/zoom.less | 8 +- src/theme/index.ts | 19 +- src/utils/Storage.ts | 66 +++---- src/utils/dateUtil.ts | 10 +- src/utils/domUtils.ts | 172 ++++++++++-------- src/utils/env.ts | 40 ++--- src/utils/http/axios/Axios.ts | 176 +++++++++--------- src/utils/http/axios/axiosCancel.ts | 48 ++--- src/utils/http/axios/axiosTransform.ts | 24 +-- src/utils/http/axios/checkStatus.ts | 52 +++--- src/utils/http/axios/helper.ts | 29 +-- src/utils/http/axios/index.ts | 209 +++++++++++----------- src/utils/http/axios/types.ts | 64 +++---- src/utils/index.ts | 74 ++++---- src/utils/is/index.ts | 68 +++---- src/utils/lib/echarts.ts | 38 ++-- src/utils/log.ts | 6 +- src/utils/urlUtils.ts | 17 +- src/views/dashboard/index.vue | 98 +++++----- src/views/exception/403.vue | 51 +++--- src/views/exception/404.vue | 45 ++--- src/views/exception/500.vue | 51 +++--- src/views/login/ForgetPasswordForm.vue | 73 ++++---- src/views/login/Login.vue | 26 +-- src/views/login/LoginForm.vue | 119 ++++++------ src/views/login/LoginTitle.vue | 10 +- src/views/login/LoginWave.vue | 100 +++++------ src/views/login/RegisterForm.vue | 105 +++++------ src/views/login/useLogin.ts | 58 +++--- src/views/message/barChart.vue | 175 +++++++++--------- src/views/message/index.vue | 6 +- src/views/message/lineChart.vue | 195 ++++++++++---------- src/views/message/pieChart.vue | 107 +++++------ src/views/my/AccountSetting.vue | 28 +-- src/views/my/ChangePassword.vue | 4 +- src/views/my/EditNickname.vue | 103 +++++------ src/views/my/EditSign.vue | 79 ++++---- src/views/my/EditUserInfo.vue | 132 +++++++------- src/views/my/ThemeSetting.vue | 82 ++++----- src/views/my/components/NavBar.vue | 16 +- src/views/my/components/UploaderImage.vue | 24 +-- src/views/my/index.vue | 107 +++++------ src/views/my/pickColumns.ts | 8 +- src/views/welcome/index.vue | 132 +++++++------- tsconfig.json | 28 +-- types/config.d.ts | 32 ++-- types/global.d.ts | 78 ++++---- types/index.d.ts | 26 +-- types/modules.d.ts | 8 +- uno.config.ts | 10 +- vite.config.ts | 47 ++--- 104 files changed, 2524 insertions(+), 2388 deletions(-) rename postcss.config.cjs => postcss.config.js (90%) diff --git a/build/constant.ts b/build/constant.ts index 71697bf..01d1a18 100644 --- a/build/constant.ts +++ b/build/constant.ts @@ -1,6 +1,6 @@ /** * The name of the configuration file entered in the production environment */ -export const GLOB_CONFIG_FILE_NAME = 'app.config.js'; +export const GLOB_CONFIG_FILE_NAME = 'app.config.js' -export const OUTPUT_DIR = 'dist/vant-mobile'; +export const OUTPUT_DIR = 'dist/vant-mobile' diff --git a/build/getConfigFileName.ts b/build/getConfigFileName.ts index d61cd41..edcf56e 100644 --- a/build/getConfigFileName.ts +++ b/build/getConfigFileName.ts @@ -2,8 +2,8 @@ * Get the configuration file variable name * @param env */ -export const getConfigFileName = (env: Record) => { +export function getConfigFileName(env: Record) { return `__PRODUCTION__${env.VITE_GLOB_APP_SHORT_NAME || '__APP'}__CONF__` .toUpperCase() - .replace(/\s/g, ''); -}; + .replace(/\s/g, '') +} diff --git a/build/script/buildConf.ts b/build/script/buildConf.ts index d228816..b54676c 100644 --- a/build/script/buildConf.ts +++ b/build/script/buildConf.ts @@ -1,24 +1,24 @@ /** * Generate additional configuration files when used for packaging. The file can be configured with some global variables, so that it can be changed directly externally without repackaging */ -import { GLOB_CONFIG_FILE_NAME, OUTPUT_DIR } from '../constant'; -import fs from 'fs-extra'; -import colors from 'picocolors'; +import fs from 'fs-extra' +import colors from 'picocolors' +import { GLOB_CONFIG_FILE_NAME, OUTPUT_DIR } from '../constant' -import { getRootPath, getEnvConfig } from '../utils'; -import { getConfigFileName } from '../getConfigFileName'; +import { getEnvConfig, getRootPath } from '../utils' +import { getConfigFileName } from '../getConfigFileName' -import pkg from '../../package.json'; +import pkg from '../../package.json' function createConfig( { configName, config, configFileName = GLOB_CONFIG_FILE_NAME, - }: { configName: string; config: any; configFileName?: string } = { configName: '', config: {} } + }: { configName: string, config: any, configFileName?: string } = { configName: '', config: {} }, ) { try { - const windowConf = `window.${configName}`; + const windowConf = `window.${configName}` // Ensure that the variable will not be modified const configStr = `${windowConf}=${JSON.stringify(config)}; Object.freeze(${windowConf}); @@ -26,19 +26,20 @@ function createConfig( configurable: false, writable: false, }); - `.replace(/\s/g, ''); - fs.mkdirp(getRootPath(OUTPUT_DIR)); - fs.writeFileSync(getRootPath(`${OUTPUT_DIR}/${configFileName}`), configStr); + `.replace(/\s/g, '') + fs.mkdirp(getRootPath(OUTPUT_DIR)) + fs.writeFileSync(getRootPath(`${OUTPUT_DIR}/${configFileName}`), configStr) - console.log(colors.cyan(`✨ [${pkg.name}]`) + ` - configuration file is build successfully:`); - console.log(colors.gray(OUTPUT_DIR + '/' + colors.green(configFileName)) + '\n'); - } catch (error) { - console.log(colors.red('configuration file configuration file failed to package:\n' + error)); + console.log(`${colors.cyan(`✨ [${pkg.name}]`)} - configuration file is build successfully:`) + console.log(`${colors.gray(`${OUTPUT_DIR}/${colors.green(configFileName)}`)}\n`) + } + catch (error) { + console.log(colors.red(`configuration file configuration file failed to package:\n${error}`)) } } export function runBuildConfig() { - const config = getEnvConfig(); - const configFileName = getConfigFileName(config); - createConfig({ config, configName: configFileName }); + const config = getEnvConfig() + const configFileName = getConfigFileName(config) + createConfig({ config, configName: configFileName }) } diff --git a/build/script/postBuild.ts b/build/script/postBuild.ts index 3c440e9..8c48955 100644 --- a/build/script/postBuild.ts +++ b/build/script/postBuild.ts @@ -1,23 +1,24 @@ // #!/usr/bin/env node -import { runBuildConfig } from './buildConf'; -import colors from 'picocolors'; +import colors from 'picocolors' -import pkg from '../../package.json'; +import pkg from '../../package.json' +import { runBuildConfig } from './buildConf' -export const runBuild = async () => { +export async function runBuild() { try { - const argvList = process.argv.splice(2); + const argvList = process.argv.splice(2) // Generate configuration file if (!argvList.includes('disabled-config')) { - await runBuildConfig(); + await runBuildConfig() } - console.log(`✨ ${colors.cyan(`[${pkg.name}]`)}` + ' - build successfully!'); - } catch (error) { - console.log(colors.red('vite build error:\n' + error)); - process.exit(1); + console.log(`✨ ${colors.cyan(`[${pkg.name}]`)} - build successfully!`) } -}; -runBuild(); + catch (error) { + console.log(colors.red(`vite build error:\n${error}`)) + process.exit(1) + } +} +runBuild() diff --git a/build/utils.ts b/build/utils.ts index 4499e96..86e8474 100644 --- a/build/utils.ts +++ b/build/utils.ts @@ -1,44 +1,45 @@ -import fs from 'fs'; -import path from 'path'; -import dotenv from 'dotenv'; +import fs from 'node:fs' +import path from 'node:path' +import dotenv from 'dotenv' export function isDevFn(mode: string): boolean { - return mode === 'development'; + return mode === 'development' } export function isProdFn(mode: string): boolean { - return mode === 'production'; + return mode === 'production' } /** * Whether to generate package preview */ export function isReportMode(): boolean { - return process.env.REPORT === 'true'; + return process.env.REPORT === 'true' } // Read all environment variable configuration files to process.env // 读取并处理所有环境变量配置文件 .env export function wrapperEnv(envConf: Recordable): ViteEnv { - const ret: any = {}; + const ret: any = {} for (const envName of Object.keys(envConf)) { // 去除空格 - let realName = envConf[envName].replace(/\\n/g, '\n'); - realName = realName === 'true' ? true : realName === 'false' ? false : realName; + let realName = envConf[envName].replace(/\\n/g, '\n') + realName = realName === 'true' ? true : realName === 'false' ? false : realName if (envName === 'VITE_PORT') { - realName = Number(realName); + realName = Number(realName) } if (envName === 'VITE_PROXY') { try { - realName = JSON.parse(realName); - } catch (error) {} + realName = JSON.parse(realName) + } + catch (error) {} } - ret[envName] = realName; - process.env[envName] = realName; + ret[envName] = realName + process.env[envName] = realName } - return ret; + return ret } /** @@ -47,21 +48,22 @@ export function wrapperEnv(envConf: Recordable): ViteEnv { * @param confFiles ext */ export function getEnvConfig(match = 'VITE_GLOB_', confFiles = ['.env', '.env.production']) { - let envConfig = {}; + let envConfig = {} confFiles.forEach((item) => { try { - const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), item))); - envConfig = { ...envConfig, ...env }; - } catch (error) {} - }); + const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), item))) + envConfig = { ...envConfig, ...env } + } + catch (error) {} + }) Object.keys(envConfig).forEach((key) => { - const reg = new RegExp(`^(${match})`); + const reg = new RegExp(`^(${match})`) if (!reg.test(key)) { - Reflect.deleteProperty(envConfig, key); + Reflect.deleteProperty(envConfig, key) } - }); - return envConfig; + }) + return envConfig } /** @@ -69,5 +71,5 @@ export function getEnvConfig(match = 'VITE_GLOB_', confFiles = ['.env', '.env.pr * @param dir file path */ export function getRootPath(...dir: string[]) { - return path.resolve(process.cwd(), ...dir); + return path.resolve(process.cwd(), ...dir) } diff --git a/build/vite/plugin/compress.ts b/build/vite/plugin/compress.ts index 9f8e66e..74e870e 100644 --- a/build/vite/plugin/compress.ts +++ b/build/vite/plugin/compress.ts @@ -2,25 +2,25 @@ * Used to package and output gzip. Note that this does not work properly in Vite, the specific reason is still being investigated * https://github.com/anncwb/vite-plugin-compression */ -import type { PluginOption } from 'vite'; +import type { PluginOption } from 'vite' -import compressPlugin from 'vite-plugin-compression'; +import compressPlugin from 'vite-plugin-compression' export function configCompressPlugin( compress: 'gzip' | 'brotli' | 'none', - deleteOriginFile = false + deleteOriginFile = false, ): PluginOption | PluginOption[] { - const compressList = compress.split(','); + const compressList = compress.split(',') - const plugins: PluginOption[] = []; + const plugins: PluginOption[] = [] if (compressList.includes('gzip')) { plugins.push( compressPlugin({ ext: '.gz', deleteOriginFile, - }) - ); + }), + ) } if (compressList.includes('brotli')) { plugins.push( @@ -28,8 +28,8 @@ export function configCompressPlugin( ext: '.br', algorithm: 'brotliCompress', deleteOriginFile, - }) - ); + }), + ) } - return plugins; + return plugins } diff --git a/build/vite/plugin/html.ts b/build/vite/plugin/html.ts index 18063c8..583acbe 100644 --- a/build/vite/plugin/html.ts +++ b/build/vite/plugin/html.ts @@ -2,19 +2,19 @@ * Plugin to minimize and use ejs template syntax in index.html. * https://github.com/anncwb/vite-plugin-html */ -import type { PluginOption } from 'vite'; -import { createHtmlPlugin } from 'vite-plugin-html'; -import pkg from '../../../package.json'; -import { GLOB_CONFIG_FILE_NAME } from '../../constant'; +import type { PluginOption } from 'vite' +import { createHtmlPlugin } from 'vite-plugin-html' +import pkg from '../../../package.json' +import { GLOB_CONFIG_FILE_NAME } from '../../constant' export function configHtmlPlugin(env: ViteEnv, isBuild: boolean) { - const { VITE_GLOB_APP_TITLE, VITE_PUBLIC_PATH } = env; + const { VITE_GLOB_APP_TITLE, VITE_PUBLIC_PATH } = env - const path = VITE_PUBLIC_PATH.endsWith('/') ? VITE_PUBLIC_PATH : `${VITE_PUBLIC_PATH}/`; + const path = VITE_PUBLIC_PATH.endsWith('/') ? VITE_PUBLIC_PATH : `${VITE_PUBLIC_PATH}/` const getAppConfigSrc = () => { - return `${path || '/'}${GLOB_CONFIG_FILE_NAME}?v=${pkg.version}-${new Date().getTime()}`; - }; + return `${path || '/'}${GLOB_CONFIG_FILE_NAME}?v=${pkg.version}-${new Date().getTime()}` + } // 当执行 yarn build 构建项目之后,会自动生成 _app.config.js 文件并插入 index.html // _app.config.js 用于项目在打包后,需要动态修改配置的需求,如接口地址 @@ -41,6 +41,6 @@ export function configHtmlPlugin(env: ViteEnv, isBuild: boolean) { ] : [], }, - }); - return htmlPlugin; + }) + return htmlPlugin } diff --git a/build/vite/plugin/index.ts b/build/vite/plugin/index.ts index bd9fe69..5bd1e48 100644 --- a/build/vite/plugin/index.ts +++ b/build/vite/plugin/index.ts @@ -1,14 +1,14 @@ -import type { PluginOption } from 'vite'; -import Components from 'unplugin-vue-components/vite'; -import { VantResolver } from 'unplugin-vue-components/resolvers'; -import vue from '@vitejs/plugin-vue'; -import UnoCSS from 'unocss/vite'; +import type { PluginOption } from 'vite' +import Components from 'unplugin-vue-components/vite' +import { VantResolver } from 'unplugin-vue-components/resolvers' +import vue from '@vitejs/plugin-vue' +import UnoCSS from 'unocss/vite' -import { configHtmlPlugin } from './html'; -import { configMockPlugin } from './mock'; -import { configCompressPlugin } from './compress'; -import { configVisualizerConfig } from './visualizer'; -import { configSvgIconsPlugin } from './svgSprite'; +import { configHtmlPlugin } from './html' +import { configMockPlugin } from './mock' +import { configCompressPlugin } from './compress' +import { configVisualizerConfig } from './visualizer' +import { configSvgIconsPlugin } from './svgSprite' /** * 配置 vite 插件 @@ -22,7 +22,7 @@ export function createVitePlugins(viteEnv: ViteEnv, isBuild: boolean, prodMock: // 如果你需要多种形式,你可以用','来分隔 // VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE 打包使用压缩时是否删除原始文件,默认为 false - const { VITE_USE_MOCK, VITE_BUILD_COMPRESS, VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE } = viteEnv; + const { VITE_USE_MOCK, VITE_BUILD_COMPRESS, VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE } = viteEnv const vitePlugins: (PluginOption | PluginOption[])[] = [ // have to @@ -33,30 +33,30 @@ export function createVitePlugins(viteEnv: ViteEnv, isBuild: boolean, prodMock: resolvers: [VantResolver()], types: [], }), - ]; + ] // UnoCSS - vitePlugins.push(UnoCSS()); + vitePlugins.push(UnoCSS()) // 加载 html 插件 vite-plugin-html - vitePlugins.push(configHtmlPlugin(viteEnv, isBuild)); + vitePlugins.push(configHtmlPlugin(viteEnv, isBuild)) // rollup-plugin-visualizer - vitePlugins.push(configVisualizerConfig()); + vitePlugins.push(configVisualizerConfig()) // vite-plugin-mock - VITE_USE_MOCK && vitePlugins.push(configMockPlugin(isBuild, prodMock)); + VITE_USE_MOCK && vitePlugins.push(configMockPlugin(isBuild, prodMock)) // vite-plugin-svg-icons - vitePlugins.push(configSvgIconsPlugin(isBuild)); + vitePlugins.push(configSvgIconsPlugin(isBuild)) if (isBuild) { // rollup-plugin-gzip // 加载 gzip 打包 vitePlugins.push( - configCompressPlugin(VITE_BUILD_COMPRESS, VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE) - ); + configCompressPlugin(VITE_BUILD_COMPRESS, VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE), + ) } - return vitePlugins; + return vitePlugins } diff --git a/build/vite/plugin/mock.ts b/build/vite/plugin/mock.ts index 6e0ded3..9b79433 100644 --- a/build/vite/plugin/mock.ts +++ b/build/vite/plugin/mock.ts @@ -2,7 +2,7 @@ * Mock plugin for development and production. * https://github.com/anncwb/vite-plugin-mock */ -import { viteMockServe } from 'vite-plugin-mock'; +import { viteMockServe } from 'vite-plugin-mock' export function configMockPlugin(isBuild: boolean, prodMock: boolean) { return viteMockServe({ @@ -15,5 +15,5 @@ export function configMockPlugin(isBuild: boolean, prodMock: boolean) { setupProdMockServer(); `, - }); + }) } diff --git a/build/vite/plugin/svgSprite.ts b/build/vite/plugin/svgSprite.ts index 5b3097e..3e2680a 100644 --- a/build/vite/plugin/svgSprite.ts +++ b/build/vite/plugin/svgSprite.ts @@ -3,8 +3,8 @@ * https://github.com/anncwb/vite-plugin-svg-icons */ -import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'; -import path from 'path'; +import path from 'node:path' +import { createSvgIconsPlugin } from 'vite-plugin-svg-icons' export function configSvgIconsPlugin(isBuild: boolean) { // 指定需要缓存的图标文件夹 @@ -14,6 +14,6 @@ export function configSvgIconsPlugin(isBuild: boolean) { svgoOptions: isBuild, // 指定symbolId格式 symbolId: 'icon-[dir]-[name]', - }); - return svgIconsPlugin; + }) + return svgIconsPlugin } diff --git a/build/vite/plugin/visualizer.ts b/build/vite/plugin/visualizer.ts index 25caa46..eb392a5 100644 --- a/build/vite/plugin/visualizer.ts +++ b/build/vite/plugin/visualizer.ts @@ -1,9 +1,9 @@ /** * Package file volume analysis */ -import visualizer from 'rollup-plugin-visualizer'; -import type { PluginOption } from 'vite'; -import { isReportMode } from '../../utils'; +import visualizer from 'rollup-plugin-visualizer' +import type { PluginOption } from 'vite' +import { isReportMode } from '../../utils' export function configVisualizerConfig() { if (isReportMode()) { @@ -12,7 +12,7 @@ export function configVisualizerConfig() { open: true, gzipSize: true, brotliSize: true, - }) as PluginOption; + }) as PluginOption } - return []; + return [] } diff --git a/build/vite/proxy.ts b/build/vite/proxy.ts index 53d050c..55e4e34 100644 --- a/build/vite/proxy.ts +++ b/build/vite/proxy.ts @@ -1,38 +1,38 @@ /** * Used to parse the .env.development proxy configuration */ -import type { ProxyOptions } from 'vite'; +import type { ProxyOptions } from 'vite' -type ProxyItem = [string, string]; +type ProxyItem = [string, string] -type ProxyList = ProxyItem[]; +type ProxyList = ProxyItem[] -type ProxyTargetList = Record string }>; +type ProxyTargetList = Record string }> -const httpsRE = /^https:\/\//; +const httpsRE = /^https:\/\// /** * Generate proxy * @param list */ export function createProxy(list: ProxyList = []) { - const ret: ProxyTargetList = {}; + const ret: ProxyTargetList = {} for (const [prefix, target] of list) { - const isHttps = httpsRE.test(target); + const isHttps = httpsRE.test(target) // https://github.com/http-party/node-http-proxy#options ret[prefix] = { - target: target, + target, changeOrigin: true, ws: true, - rewrite: (path) => path.replace(new RegExp(`^${prefix}`), ''), + rewrite: path => path.replace(new RegExp(`^${prefix}`), ''), // https is require secure=false // 如果您secure="true"只允许来自 HTTPS 的请求,则secure="false"意味着允许来自 HTTP 和 HTTPS 的请求。 ...(isHttps ? { secure: false } : {}), - }; + } } - return ret; + return ret // ret // { diff --git a/commitlint.config.cjs b/commitlint.config.cjs index c49163d..5668c68 100644 --- a/commitlint.config.cjs +++ b/commitlint.config.cjs @@ -1,26 +1,26 @@ // commitlint.config.js -const fs = require('fs'); -const path = require('path'); -const { execSync } = require('child_process'); +const fs = require('node:fs') +const path = require('node:path') +const { execSync } = require('node:child_process') const scopes = fs .readdirSync(path.resolve(__dirname, 'src'), { withFileTypes: true }) - .filter((dirent) => dirent.isDirectory()) - .map((dirent) => dirent.name.replace(/s$/, '')); + .filter(dirent => dirent.isDirectory()) + .map(dirent => dirent.name.replace(/s$/, '')) // precomputed scope const scopeComplete = execSync('git status --porcelain || true') .toString() .trim() .split('\n') - .find((r) => ~r.indexOf('M src')) + .find(r => ~r.indexOf('M src')) ?.replace(/(\/)/g, '%%') ?.match(/src%%((\w|-)*)/)?.[1] - ?.replace(/s$/, ''); + ?.replace(/s$/, '') /** @type {import('cz-git').UserConfig} */ module.exports = { - ignores: [(commit) => commit.includes('init')], + ignores: [commit => commit.includes('init')], extends: ['@commitlint/config-conventional'], rules: { 'body-leading-blank': [2, 'always'], @@ -144,12 +144,12 @@ module.exports = { emptyIssuePrefixsAlias: 'skip', customIssuePrefixsAlias: 'custom', confirmColorize: true, - maxHeaderLength: Infinity, - maxSubjectLength: Infinity, + maxHeaderLength: Number.POSITIVE_INFINITY, + maxSubjectLength: Number.POSITIVE_INFINITY, minSubjectLength: 0, scopeOverrides: undefined, defaultBody: '', defaultIssues: '', defaultSubject: '', }, -}; +} diff --git a/index.html b/index.html index c519316..ccfcc16 100644 --- a/index.html +++ b/index.html @@ -1,27 +1,26 @@ - + - - <%= title %> - + <%= title %>
diff --git a/mock/_createProductionServer.ts b/mock/_createProductionServer.ts index 74125af..0588dae 100644 --- a/mock/_createProductionServer.ts +++ b/mock/_createProductionServer.ts @@ -1,18 +1,18 @@ -import { createProdMockServer } from 'vite-plugin-mock/es/createProdMockServer'; +import { createProdMockServer } from 'vite-plugin-mock/es/createProdMockServer' -const modules = import.meta.glob('./**/*.ts', { eager: true }) as any; +const modules = import.meta.glob('./**/*.ts', { eager: true }) as any -const mockModules: any[] = []; +const mockModules: any[] = [] Object.keys(modules).forEach((key) => { if (key.includes('/_')) { - return; + return } - mockModules.push(...modules[key].default); -}); + mockModules.push(...modules[key].default) +}) /** * Used in a production environment. Need to manually import all modules */ export function setupProdMockServer() { - createProdMockServer(mockModules); + createProdMockServer(mockModules) } diff --git a/mock/_util.ts b/mock/_util.ts index e947627..9039db9 100644 --- a/mock/_util.ts +++ b/mock/_util.ts @@ -1,5 +1,5 @@ -import Mock from 'mockjs'; -import { ResultEnum } from '@/enums/httpEnum'; +import Mock from 'mockjs' +import { ResultEnum } from '@/enums/httpEnum' export function resultSuccess(result: T, { message = 'ok' } = {}) { return Mock.mock({ @@ -7,16 +7,16 @@ export function resultSuccess(result: T, { message = 'ok' } = {} result, message, type: 'success', - }); + }) } export function resultPageSuccess( page: number, pageSize: number, list: T[], - { message = 'ok' } = {} + { message = 'ok' } = {}, ) { - const pageData = pagination(page, pageSize, list); + const pageData = pagination(page, pageSize, list) return { ...resultSuccess({ @@ -26,46 +26,46 @@ export function resultPageSuccess( list: pageData, }), message, - }; + } } export function resultError( message = 'Request failed', - { code = ResultEnum.ERROR, result = null } = {} + { code = ResultEnum.ERROR, result = null } = {}, ) { return { code, result, message, type: 'error', - }; + } } export function pagination(pageNo: number, pageSize: number, array: T[]): T[] { - const offset = (pageNo - 1) * Number(pageSize); - const ret = - offset + Number(pageSize) >= array.length + const offset = (pageNo - 1) * Number(pageSize) + const ret + = offset + Number(pageSize) >= array.length ? array.slice(offset, array.length) - : array.slice(offset, offset + Number(pageSize)); - return ret; + : array.slice(offset, offset + Number(pageSize)) + return ret } /** - * @param {Number} times 回调函数需要执行的次数 + * @param {number} times 回调函数需要执行的次数 * @param {Function} callback 回调函数 */ export function doCustomTimes(times: number, callback: any) { - let i = -1; + let i = -1 while (++i < times) { - callback(i); + callback(i) } } export interface requestParams { - method: string; - body: any; - headers?: { authorization?: string }; - query: any; + method: string + body: any + headers?: { authorization?: string } + query: any } /** @@ -73,5 +73,5 @@ export interface requestParams { * */ export function getRequestToken({ headers }: requestParams): string | undefined { - return headers?.authorization; + return headers?.authorization } diff --git a/mock/user/user.ts b/mock/user/user.ts index 48dd380..8bc15a3 100644 --- a/mock/user/user.ts +++ b/mock/user/user.ts @@ -1,6 +1,7 @@ -import { MockMethod } from 'vite-plugin-mock'; -import { getRequestToken, requestParams, resultError, resultSuccess } from '../_util'; -import { ResultEnum } from '@/enums/httpEnum'; +import type { MockMethod } from 'vite-plugin-mock' +import type { requestParams } from '../_util' +import { getRequestToken, resultError, resultSuccess } from '../_util' +import { ResultEnum } from '@/enums/httpEnum' const fakeUserList = [ { @@ -32,7 +33,7 @@ const fakeUserList = [ phone: '18822137893', token: 'fakeToken2', }, -]; +] export default [ { @@ -40,21 +41,21 @@ export default [ timeout: 1000, method: 'post', response: ({ body }) => { - const { username, password } = body; + const { username, password } = body const checkUser = fakeUserList.find( - (item) => item.username === username && password === item.password - ); + item => item.username === username && password === item.password, + ) if (!checkUser) { - return resultError('帐号或密码不正确'); + return resultError('帐号或密码不正确') } - const { userId, username: _username, token, realname, sign } = checkUser; + const { userId, username: _username, token, realname, sign } = checkUser return resultSuccess({ userId, username: _username, token, realname, sign, - }); + }) }, }, { @@ -62,15 +63,17 @@ export default [ timeout: 1000, method: 'get', response: (request: requestParams) => { - const token = getRequestToken(request); - if (!token) return resultError('无效令牌'); - const checkUser = fakeUserList.find((item) => item.token === token); + const token = getRequestToken(request) + if (!token) { + return resultError('无效令牌') + } + const checkUser = fakeUserList.find(item => item.token === token) if (!checkUser) { return resultError('没有获取到对应的用户信息', { code: ResultEnum.TOKEN_EXPIRED, - }); + }) } - return resultSuccess(checkUser); + return resultSuccess(checkUser) }, }, { @@ -78,13 +81,15 @@ export default [ timeout: 1000, method: 'post', response: (request: requestParams) => { - const token = getRequestToken(request); - if (!token) return resultError('无效令牌'); - const checkUser = fakeUserList.find((item) => item.token === token); - if (!checkUser) { - return resultError('无效令牌'); + const token = getRequestToken(request) + if (!token) { + return resultError('无效令牌') } - return resultSuccess(undefined, { message: '令牌已被销毁' }); + const checkUser = fakeUserList.find(item => item.token === token) + if (!checkUser) { + return resultError('无效令牌') + } + return resultSuccess(undefined, { message: '令牌已被销毁' }) }, }, -] as MockMethod[]; +] as MockMethod[] diff --git a/postcss.config.cjs b/postcss.config.js similarity index 90% rename from postcss.config.cjs rename to postcss.config.js index 9ec479f..2b2d256 100644 --- a/postcss.config.cjs +++ b/postcss.config.js @@ -15,8 +15,8 @@ // 所有*.js文件现在都解释为 ESM,并且需要使用 ESM 语法。您可以使用扩展名重命名文件.cjs来继续使用 CJS。 // require 是cjs 语法 -const autoprefixer = require('autoprefixer'); -const viewport = require('postcss-mobile-forever'); +import autoprefixer from 'autoprefixer' +import viewport from 'postcss-mobile-forever' const baseViewportOpts = { appSelector: '#app', // 根元素选择器,用于设置桌面端和横屏时的居中样式 @@ -37,16 +37,16 @@ const baseViewportOpts = { // exclude: [/node_modules/], // 忽略某些文件夹下的文件或特定文件 // include: [/src/], // 如果设置了include,那将只有匹配到的文件才会被转换 mobileUnit: 'vw', // 指定需要转换成的视口单位,建议使用 vw - rootContainingBlockSelectorList: ["van-popup--bottom"], // 指定包含块是根包含块的选择器,这种选择器的定位通常是 `fixed`,但是选择器内没有 `position: fixed` -}; + rootContainingBlockSelectorList: ['van-popup--bottom'], // 指定包含块是根包含块的选择器,这种选择器的定位通常是 `fixed`,但是选择器内没有 `position: fixed` +} -module.exports = { +export default { plugins: [ autoprefixer(), viewport({ ...baseViewportOpts, // 只将 vant 转为 350 设计稿的 viewport,其它样式的视图宽度为 750 - viewportWidth: (file) => (file.includes('node_modules/vant/') ? 375 : 750), + viewportWidth: file => (file.includes('node_modules/vant/') ? 375 : 750), }), ], -}; +} diff --git a/src/App.vue b/src/App.vue index d4f3b50..e2aaaeb 100644 --- a/src/App.vue +++ b/src/App.vue @@ -1,7 +1,7 @@ diff --git a/src/enums/breakpointEnum.ts b/src/enums/breakpointEnum.ts index 93acc1a..fa42ea3 100644 --- a/src/enums/breakpointEnum.ts +++ b/src/enums/breakpointEnum.ts @@ -16,13 +16,13 @@ export enum screenEnum { XXL = 1600, } -const screenMap = new Map(); +const screenMap = new Map() -screenMap.set(sizeEnum.XS, screenEnum.XS); -screenMap.set(sizeEnum.SM, screenEnum.SM); -screenMap.set(sizeEnum.MD, screenEnum.MD); -screenMap.set(sizeEnum.LG, screenEnum.LG); -screenMap.set(sizeEnum.XL, screenEnum.XL); -screenMap.set(sizeEnum.XXL, screenEnum.XXL); +screenMap.set(sizeEnum.XS, screenEnum.XS) +screenMap.set(sizeEnum.SM, screenEnum.SM) +screenMap.set(sizeEnum.MD, screenEnum.MD) +screenMap.set(sizeEnum.LG, screenEnum.LG) +screenMap.set(sizeEnum.XL, screenEnum.XL) +screenMap.set(sizeEnum.XXL, screenEnum.XXL) -export { screenMap }; +export { screenMap } diff --git a/src/enums/cacheEnum.ts b/src/enums/cacheEnum.ts index 7a2458a..7a96b03 100644 --- a/src/enums/cacheEnum.ts +++ b/src/enums/cacheEnum.ts @@ -1,14 +1,14 @@ // token key -export const TOKEN_KEY = 'TOKEN'; +export const TOKEN_KEY = 'TOKEN' // user info key -export const USER_INFO_KEY = 'USER__INFO__'; +export const USER_INFO_KEY = 'USER__INFO__' // role info key -export const ROLES_KEY = 'ROLES__KEY__'; +export const ROLES_KEY = 'ROLES__KEY__' // base global local key -export const BASE_LOCAL_CACHE_KEY = 'LOCAL__CACHE__KEY__'; +export const BASE_LOCAL_CACHE_KEY = 'LOCAL__CACHE__KEY__' // base global session key -export const BASE_SESSION_CACHE_KEY = 'SESSION__CACHE__KEY__'; +export const BASE_SESSION_CACHE_KEY = 'SESSION__CACHE__KEY__' diff --git a/src/enums/pageEnum.ts b/src/enums/pageEnum.ts index 7c4cd81..42b59e1 100644 --- a/src/enums/pageEnum.ts +++ b/src/enums/pageEnum.ts @@ -1,3 +1,4 @@ +/* eslint-disable ts/no-duplicate-enum-values */ export enum PageEnum { // 登录 BASE_LOGIN = '/login', diff --git a/src/hooks/core/useTimeout.ts b/src/hooks/core/useTimeout.ts index dc352c9..eea8b4b 100644 --- a/src/hooks/core/useTimeout.ts +++ b/src/hooks/core/useTimeout.ts @@ -1,47 +1,48 @@ -import { ref, watch } from 'vue'; -import { tryOnUnmounted } from '@vueuse/core'; -import { isFunction } from '@/utils/is'; +import { ref, watch } from 'vue' +import { tryOnUnmounted } from '@vueuse/core' +import { isFunction } from '@/utils/is' export function useTimeoutFn(handle: Fn, wait: number, native = false) { if (!isFunction(handle)) { - throw new Error('handle is not Function!'); + throw new Error('handle is not Function!') } - const { readyRef, stop, start } = useTimeoutRef(wait); + const { readyRef, stop, start } = useTimeoutRef(wait) if (native) { - handle(); - } else { + handle() + } + else { watch( readyRef, (maturity) => { - maturity && handle(); + maturity && handle() }, - { immediate: false } - ); + { immediate: false }, + ) } - return { readyRef, stop, start }; + return { readyRef, stop, start } } export function useTimeoutRef(wait: number) { - const readyRef = ref(false); + const readyRef = ref(false) - let timer: TimeoutHandle; + let timer: TimeoutHandle function stop(): void { - readyRef.value = false; - timer && window.clearTimeout(timer); + readyRef.value = false + timer && window.clearTimeout(timer) } function start(): void { - stop(); + stop() timer = setTimeout(() => { - readyRef.value = true; - }, wait); + readyRef.value = true + }, wait) } - start(); + start() - tryOnUnmounted(stop); + tryOnUnmounted(stop) - return { readyRef, stop, start }; + return { readyRef, stop, start } } diff --git a/src/hooks/event/useBreakpoint.ts b/src/hooks/event/useBreakpoint.ts index 4b2d29c..b8dd00b 100644 --- a/src/hooks/event/useBreakpoint.ts +++ b/src/hooks/event/useBreakpoint.ts @@ -1,18 +1,19 @@ -import { ref, computed, ComputedRef, unref } from 'vue'; -import { useEventListener } from '@/hooks/event/useEventListener'; -import { screenMap, sizeEnum, screenEnum } from '@/enums/breakpointEnum'; +import type { ComputedRef } from 'vue' +import { computed, ref, unref } from 'vue' +import { useEventListener } from '@/hooks/event/useEventListener' +import { screenEnum, screenMap, sizeEnum } from '@/enums/breakpointEnum' -let globalScreenRef: ComputedRef; -let globalWidthRef: ComputedRef; -let globalRealWidthRef: ComputedRef; +let globalScreenRef: ComputedRef +let globalWidthRef: ComputedRef +let globalRealWidthRef: ComputedRef export interface CreateCallbackParams { - screen: ComputedRef; - width: ComputedRef; - realWidth: ComputedRef; - screenEnum: typeof screenEnum; - screenMap: Map; - sizeEnum: typeof sizeEnum; + screen: ComputedRef + width: ComputedRef + realWidth: ComputedRef + screenEnum: typeof screenEnum + screenMap: Map + sizeEnum: typeof sizeEnum } export function useBreakpoint() { @@ -21,35 +22,40 @@ export function useBreakpoint() { widthRef: globalWidthRef, screenEnum, realWidthRef: globalRealWidthRef, - }; + } } // Just call it once export function createBreakpointListen(fn?: (opt: CreateCallbackParams) => void) { - const screenRef = ref(sizeEnum.XL); - const realWidthRef = ref(window.innerWidth); + const screenRef = ref(sizeEnum.XL) + const realWidthRef = ref(window.innerWidth) function getWindowWidth() { - const width = document.body.clientWidth; - const xs = screenMap.get(sizeEnum.XS)!; - const sm = screenMap.get(sizeEnum.SM)!; - const md = screenMap.get(sizeEnum.MD)!; - const lg = screenMap.get(sizeEnum.LG)!; - const xl = screenMap.get(sizeEnum.XL)!; + const width = document.body.clientWidth + const xs = screenMap.get(sizeEnum.XS)! + const sm = screenMap.get(sizeEnum.SM)! + const md = screenMap.get(sizeEnum.MD)! + const lg = screenMap.get(sizeEnum.LG)! + const xl = screenMap.get(sizeEnum.XL)! if (width < xs) { - screenRef.value = sizeEnum.XS; - } else if (width < sm) { - screenRef.value = sizeEnum.SM; - } else if (width < md) { - screenRef.value = sizeEnum.MD; - } else if (width < lg) { - screenRef.value = sizeEnum.LG; - } else if (width < xl) { - screenRef.value = sizeEnum.XL; - } else { - screenRef.value = sizeEnum.XXL; + screenRef.value = sizeEnum.XS } - realWidthRef.value = width; + else if (width < sm) { + screenRef.value = sizeEnum.SM + } + else if (width < md) { + screenRef.value = sizeEnum.MD + } + else if (width < lg) { + screenRef.value = sizeEnum.LG + } + else if (width < xl) { + screenRef.value = sizeEnum.XL + } + else { + screenRef.value = sizeEnum.XXL + } + realWidthRef.value = width } useEventListener({ @@ -57,16 +63,16 @@ export function createBreakpointListen(fn?: (opt: CreateCallbackParams) => void) name: 'resize', listener: () => { - getWindowWidth(); - resizeFn(); + getWindowWidth() + resizeFn() }, // wait: 100, - }); + }) - getWindowWidth(); - globalScreenRef = computed(() => unref(screenRef)); - globalWidthRef = computed((): number => screenMap.get(unref(screenRef)!)!); - globalRealWidthRef = computed((): number => unref(realWidthRef)); + getWindowWidth() + globalScreenRef = computed(() => unref(screenRef)) + globalWidthRef = computed((): number => screenMap.get(unref(screenRef)!)!) + globalRealWidthRef = computed((): number => unref(realWidthRef)) function resizeFn() { fn?.({ @@ -76,14 +82,14 @@ export function createBreakpointListen(fn?: (opt: CreateCallbackParams) => void) screenEnum, screenMap, sizeEnum, - }); + }) } - resizeFn(); + resizeFn() return { screenRef: globalScreenRef, screenEnum, widthRef: globalWidthRef, realWidthRef: globalRealWidthRef, - }; + } } diff --git a/src/hooks/event/useEventListener.ts b/src/hooks/event/useEventListener.ts index 600afab..498db6c 100644 --- a/src/hooks/event/useEventListener.ts +++ b/src/hooks/event/useEventListener.ts @@ -1,18 +1,18 @@ -import type { Ref } from 'vue'; +import type { Ref } from 'vue' -import { ref, watch, unref } from 'vue'; -import { useThrottleFn, useDebounceFn } from '@vueuse/core'; +import { ref, unref, watch } from 'vue' +import { useDebounceFn, useThrottleFn } from '@vueuse/core' -export type RemoveEventFn = () => void; +export type RemoveEventFn = () => void export interface UseEventParams { - el?: Element | Ref | Window | any; - name: string; - listener: EventListener; - options?: boolean | AddEventListenerOptions; - autoRemove?: boolean; - isDebounce?: boolean; - wait?: number; + el?: Element | Ref | Window | any + name: string + listener: EventListener + options?: boolean | AddEventListenerOptions + autoRemove?: boolean + isDebounce?: boolean + wait?: number } export function useEventListener({ @@ -24,39 +24,38 @@ export function useEventListener({ isDebounce = true, wait = 80, }: UseEventParams): { removeEvent: RemoveEventFn } { - /* eslint-disable-next-line */ - let remove: RemoveEventFn = () => { - }; - const isAddRef = ref(false); + let remove: RemoveEventFn = () => { + } + const isAddRef = ref(false) if (el) { - const element: Ref = ref(el as Element); + const element: Ref = ref(el as Element) - const handler = isDebounce ? useDebounceFn(listener, wait) : useThrottleFn(listener, wait); - const realHandler = wait ? handler : listener; + const handler = isDebounce ? useDebounceFn(listener, wait) : useThrottleFn(listener, wait) + const realHandler = wait ? handler : listener const removeEventListener = (e: Element) => { - isAddRef.value = true; - e.removeEventListener(name, realHandler, options); - }; - const addEventListener = (e: Element) => e.addEventListener(name, realHandler, options); + isAddRef.value = true + e.removeEventListener(name, realHandler, options) + } + const addEventListener = (e: Element) => e.addEventListener(name, realHandler, options) const removeWatch = watch( element, (v, _ov, cleanUp) => { if (v) { - !unref(isAddRef) && addEventListener(v); + !unref(isAddRef) && addEventListener(v) cleanUp(() => { - autoRemove && removeEventListener(v); - }); + autoRemove && removeEventListener(v) + }) } }, - { immediate: true } - ); + { immediate: true }, + ) remove = () => { - removeEventListener(element.value); - removeWatch(); - }; + removeEventListener(element.value) + removeWatch() + } } - return { removeEvent: remove }; + return { removeEvent: remove } } diff --git a/src/hooks/event/useWindowSizeFn.ts b/src/hooks/event/useWindowSizeFn.ts index 7b18ca0..14c437c 100644 --- a/src/hooks/event/useWindowSizeFn.ts +++ b/src/hooks/event/useWindowSizeFn.ts @@ -1,36 +1,35 @@ -import { tryOnMounted, tryOnUnmounted } from '@vueuse/core'; -import { useDebounceFn } from '@vueuse/core'; +import { tryOnMounted, tryOnUnmounted, useDebounceFn } from '@vueuse/core' interface WindowSizeOptions { - once?: boolean; - immediate?: boolean; - listenerOptions?: AddEventListenerOptions | boolean; + once?: boolean + immediate?: boolean + listenerOptions?: AddEventListenerOptions | boolean } export function useWindowSizeFn(fn: Fn, wait = 150, options?: WindowSizeOptions) { let handler = () => { - fn(); - }; - const handleSize = useDebounceFn(handler, wait); - handler = handleSize; + fn() + } + const handleSize = useDebounceFn(handler, wait) + handler = handleSize const start = () => { if (options && options.immediate) { - handler(); + handler() } - window.addEventListener('resize', handler); - }; + window.addEventListener('resize', handler) + } const stop = () => { - window.removeEventListener('resize', handler); - }; + window.removeEventListener('resize', handler) + } tryOnMounted(() => { - start(); - }); + start() + }) tryOnUnmounted(() => { - stop(); - }); - return [start, stop]; + stop() + }) + return [start, stop] } diff --git a/src/hooks/index.ts b/src/hooks/index.ts index 81c4556..280e2cb 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -1,3 +1,3 @@ -import { useAsync } from './use-async'; +import { useAsync } from './use-async' -export { useAsync }; +export { useAsync } diff --git a/src/hooks/setting/index.ts b/src/hooks/setting/index.ts index 965b399..aab6317 100644 --- a/src/hooks/setting/index.ts +++ b/src/hooks/setting/index.ts @@ -1,8 +1,8 @@ -import { warn } from '@/utils/log'; -import { getAppEnvConfig } from '@/utils/env'; -import { GlobConfig } from '#/config'; +import { warn } from '@/utils/log' +import { getAppEnvConfig } from '@/utils/env' +import type { GlobConfig } from '#/config' -export const useGlobSetting = (): Readonly => { +export function useGlobSetting(): Readonly { const { VITE_GLOB_APP_TITLE, VITE_GLOB_APP_TITLE_CN, @@ -12,12 +12,12 @@ export const useGlobSetting = (): Readonly => { VITE_GLOB_UPLOAD_URL, VITE_GLOB_PROD_MOCK, VITE_GLOB_IMG_URL, - } = getAppEnvConfig(); + } = getAppEnvConfig() if (!/[a-zA-Z\_]*/.test(VITE_GLOB_APP_SHORT_NAME)) { warn( - `VITE_GLOB_APP_SHORT_NAME Variables can only be characters/underscores, please modify in the environment variables and re-running.` - ); + `VITE_GLOB_APP_SHORT_NAME Variables can only be characters/underscores, please modify in the environment variables and re-running.`, + ) } // Take global configuration @@ -30,6 +30,6 @@ export const useGlobSetting = (): Readonly => { uploadUrl: VITE_GLOB_UPLOAD_URL, prodMock: VITE_GLOB_PROD_MOCK, imgUrl: VITE_GLOB_IMG_URL, - }; - return glob as Readonly; -}; + } + return glob as Readonly +} diff --git a/src/hooks/setting/useDesignSetting.ts b/src/hooks/setting/useDesignSetting.ts index d53959a..328261d 100644 --- a/src/hooks/setting/useDesignSetting.ts +++ b/src/hooks/setting/useDesignSetting.ts @@ -1,18 +1,18 @@ -import { computed } from 'vue'; -import { useDesignSettingStore } from '@/store/modules/designSetting'; +import { computed } from 'vue' +import { useDesignSettingStore } from '@/store/modules/designSetting' export function useDesignSetting() { - const designStore = useDesignSettingStore(); + const designStore = useDesignSettingStore() - const getDarkMode = computed(() => designStore.darkMode); + const getDarkMode = computed(() => designStore.darkMode) - const getAppTheme = computed(() => designStore.appTheme); + const getAppTheme = computed(() => designStore.appTheme) - const getAppThemeList = computed(() => designStore.appThemeList); + const getAppThemeList = computed(() => designStore.appThemeList) - const getIsPageAnimate = computed(() => designStore.isPageAnimate); + const getIsPageAnimate = computed(() => designStore.isPageAnimate) - const getPageAnimateType = computed(() => designStore.pageAnimateType); + const getPageAnimateType = computed(() => designStore.pageAnimateType) return { getDarkMode, @@ -20,5 +20,5 @@ export function useDesignSetting() { getAppThemeList, getIsPageAnimate, getPageAnimateType, - }; + } } diff --git a/src/hooks/use-async.ts b/src/hooks/use-async.ts index 277e086..b5bc18f 100644 --- a/src/hooks/use-async.ts +++ b/src/hooks/use-async.ts @@ -1,15 +1,16 @@ -import { isReactive, isRef } from 'vue'; +import { isReactive, isRef } from 'vue' function setLoading(loading, val) { - if (loading != undefined && isRef(loading)) { - loading.value = val; - } else if (loading != undefined && isReactive(loading)) { - loading.loading = val; + if (loading !== undefined && isRef(loading)) { + loading.value = val + } + else if (loading !== undefined && isReactive(loading)) { + loading.loading = val } } -export const useAsync = async (func: Promise, loading: any): Promise => { - setLoading(loading, true); +export async function useAsync(func: Promise, loading: any): Promise { + setLoading(loading, true) - return await func.finally(() => setLoading(loading, false)); -}; + return await func.finally(() => setLoading(loading, false)) +} diff --git a/src/hooks/useDomWidth.ts b/src/hooks/useDomWidth.ts index 1a0bc5a..1e57630 100644 --- a/src/hooks/useDomWidth.ts +++ b/src/hooks/useDomWidth.ts @@ -1,23 +1,23 @@ -import { ref, onMounted, onUnmounted } from 'vue'; -import { debounce } from 'lodash-es'; +import { onMounted, onUnmounted, ref } from 'vue' +import { debounce } from 'lodash-es' /** * description: 获取页面宽度 */ export function useDomWidth() { - const domWidth = ref(window.innerWidth); + const domWidth = ref(window.innerWidth) function resize() { - domWidth.value = document.body.clientWidth; + domWidth.value = document.body.clientWidth } onMounted(() => { - window.addEventListener('resize', debounce(resize, 80)); - }); + window.addEventListener('resize', debounce(resize, 80)) + }) onUnmounted(() => { - window.removeEventListener('resize', resize); - }); + window.removeEventListener('resize', resize) + }) - return domWidth; + return domWidth } diff --git a/src/hooks/useOnline.ts b/src/hooks/useOnline.ts index f55f31f..2ade223 100644 --- a/src/hooks/useOnline.ts +++ b/src/hooks/useOnline.ts @@ -1,30 +1,30 @@ -import { ref, onMounted, onUnmounted } from 'vue'; +import { onMounted, onUnmounted, ref } from 'vue' /** * @description 用户网络是否可用 - * */ + */ export function useOnline() { - const online = ref(true); + const online = ref(true) const showStatus = (val) => { - online.value = typeof val == 'boolean' ? val : val.target.online; - }; + online.value = typeof val == 'boolean' ? val : val.target.online + } // 在页面加载后,设置正确的网络状态 - navigator.onLine ? showStatus(true) : showStatus(false); + navigator.onLine ? showStatus(true) : showStatus(false) onMounted(() => { // 开始监听网络状态的变化 - window.addEventListener('online', showStatus); + window.addEventListener('online', showStatus) - window.addEventListener('offline', showStatus); - }); + window.addEventListener('offline', showStatus) + }) onUnmounted(() => { // 移除监听网络状态的变化 - window.removeEventListener('online', showStatus); + window.removeEventListener('online', showStatus) - window.removeEventListener('offline', showStatus); - }); + window.removeEventListener('offline', showStatus) + }) - return { online }; + return { online } } diff --git a/src/hooks/useTime.ts b/src/hooks/useTime.ts index 6063383..581794b 100644 --- a/src/hooks/useTime.ts +++ b/src/hooks/useTime.ts @@ -1,33 +1,33 @@ -import { ref, onMounted, onUnmounted } from 'vue'; +import { onMounted, onUnmounted, ref } from 'vue' /** * @description 获取本地时间 */ export function useTime() { - let timer; // 定时器 - const year = ref(0); // 年份 - const month = ref(0); // 月份 - const week = ref(''); // 星期几 - const day = ref(0); // 天数 - const hour = ref(0); // 小时 - const minute = ref(0); // 分钟 - const second = ref(0); // 秒 + let timer // 定时器 + const year = ref(0) // 年份 + const month = ref(0) // 月份 + const week = ref('') // 星期几 + const day = ref(0) // 天数 + const hour = ref(0) // 小时 + const minute = ref(0) // 分钟 + const second = ref(0) // 秒 // 更新时间 const updateTime = () => { - const date = new Date(); - year.value = date.getFullYear(); - month.value = date.getMonth() + 1; - week.value = '日一二三四五六'.charAt(date.getDay()); - day.value = date.getDate(); - hour.value = - (date.getHours() + '')?.padStart(2, '0') || - new Intl.NumberFormat(undefined, { minimumIntegerDigits: 2 }).format(date.getHours()); - minute.value = - (date.getMinutes() + '')?.padStart(2, '0') || - new Intl.NumberFormat(undefined, { minimumIntegerDigits: 2 }).format(date.getMinutes()); - second.value = date.getSeconds(); - }; + const date = new Date() + year.value = date.getFullYear() + month.value = date.getMonth() + 1 + week.value = '日一二三四五六'.charAt(date.getDay()) + day.value = date.getDate() + hour.value + = (`${date.getHours()}`)?.padStart(2, '0') + || new Intl.NumberFormat(undefined, { minimumIntegerDigits: 2 }).format(date.getHours()) + minute.value + = (`${date.getMinutes()}`)?.padStart(2, '0') + || new Intl.NumberFormat(undefined, { minimumIntegerDigits: 2 }).format(date.getMinutes()) + second.value = date.getSeconds() + } // 原生时间格式化 // new Intl.DateTimeFormat('zh', { @@ -40,16 +40,16 @@ export function useTime() { // hour12: false // }).format(new Date()) - updateTime(); + updateTime() onMounted(() => { - clearInterval(timer); - timer = setInterval(() => updateTime(), 1000); - }); + clearInterval(timer) + timer = setInterval(() => updateTime(), 1000) + }) onUnmounted(() => { - clearInterval(timer); - }); + clearInterval(timer) + }) - return { month, day, hour, minute, second, week }; + return { month, day, hour, minute, second, week } } diff --git a/src/hooks/web/useECharts.ts b/src/hooks/web/useECharts.ts index 883c0ca..57a9287 100644 --- a/src/hooks/web/useECharts.ts +++ b/src/hooks/web/useECharts.ts @@ -1,111 +1,116 @@ -import type { EChartsOption } from 'echarts'; -import type { Ref } from 'vue'; +import type { EChartsOption } from 'echarts' +import type { Ref } from 'vue' -import { useTimeoutFn } from '@/hooks/core/useTimeout'; -import { Fn, tryOnUnmounted } from '@vueuse/core'; -import { unref, nextTick, watch, computed, ref } from 'vue'; -import { useDebounceFn } from '@vueuse/core'; -import { useEventListener } from '@/hooks/event/useEventListener'; -import { useBreakpoint } from '@/hooks/event/useBreakpoint'; -import { useDesignSettingStore } from '@/store/modules/designSetting'; -import echarts from '@/utils/lib/echarts'; +import type { Fn } from '@vueuse/core' +import { tryOnUnmounted, useDebounceFn } from '@vueuse/core' +import { computed, nextTick, ref, unref, watch } from 'vue' +import { useTimeoutFn } from '@/hooks/core/useTimeout' + +import { useEventListener } from '@/hooks/event/useEventListener' +import { useBreakpoint } from '@/hooks/event/useBreakpoint' +import { useDesignSettingStore } from '@/store/modules/designSetting' +import echarts from '@/utils/lib/echarts' export function useECharts( elRef: Ref, - theme: 'light' | 'dark' | 'default' = 'default' + theme: 'light' | 'dark' | 'default' = 'default', ) { - const designStore = useDesignSettingStore(); + const designStore = useDesignSettingStore() const getDarkMode = computed(() => { - return theme === 'default' ? designStore.getDarkMode : theme; - }); + return theme === 'default' ? designStore.getDarkMode : theme + }) - let chartInstance: echarts.ECharts | null = null; - let resizeFn: Fn = resize; - const cacheOptions = ref({}); - let removeResizeFn: Fn = () => {}; - resizeFn = useDebounceFn(resize, 200); + let chartInstance: echarts.ECharts | null = null + let resizeFn: Fn = resize + const cacheOptions = ref({}) + let removeResizeFn: Fn = () => {} + resizeFn = useDebounceFn(resize, 200) const getOptions = computed((): EChartsOption => { if (getDarkMode.value !== 'dark') { - return cacheOptions.value; + return cacheOptions.value } return { backgroundColor: 'transparent', ...cacheOptions.value, - }; - }); + } + }) function initCharts(t = theme) { - const el = unref(elRef); + const el = unref(elRef) if (!el || !unref(el)) { - return; + return } - chartInstance = echarts.init(el, t); + chartInstance = echarts.init(el, t) const { removeEvent } = useEventListener({ el: window, name: 'resize', listener: resizeFn, - }); - removeResizeFn = removeEvent; - const { widthRef, screenEnum } = useBreakpoint(); + }) + removeResizeFn = removeEvent + const { widthRef, screenEnum } = useBreakpoint() if (unref(widthRef) <= screenEnum.MD || el.offsetHeight === 0) { useTimeoutFn(() => { - resizeFn(); - }, 30); + resizeFn() + }, 30) } } function setOptions(options: EChartsOption, clear = true) { - cacheOptions.value = options; + cacheOptions.value = options if (unref(elRef)?.offsetHeight === 0) { useTimeoutFn(() => { - setOptions(unref(getOptions)); - }, 30); - return; + setOptions(unref(getOptions)) + }, 30) + return } nextTick(() => { useTimeoutFn(() => { if (!chartInstance) { - initCharts(getDarkMode.value as 'default'); + initCharts(getDarkMode.value as 'default') - if (!chartInstance) return; + if (!chartInstance) { + return + } } - clear && chartInstance?.clear(); + clear && chartInstance?.clear() - chartInstance?.setOption(unref(getOptions)); - }, 30); - }); + chartInstance?.setOption(unref(getOptions)) + }, 30) + }) } function resize() { - chartInstance?.resize(); + chartInstance?.resize() } watch( () => getDarkMode.value, (theme) => { if (chartInstance) { - chartInstance.dispose(); - initCharts(theme as 'default'); - setOptions(cacheOptions.value); + chartInstance.dispose() + initCharts(theme as 'default') + setOptions(cacheOptions.value) } - } - ); + }, + ) tryOnUnmounted(() => { - if (!chartInstance) return; - removeResizeFn(); - chartInstance.dispose(); - chartInstance = null; - }); + if (!chartInstance) { + return + } + removeResizeFn() + chartInstance.dispose() + chartInstance = null + }) function getInstance(): echarts.ECharts | null { if (!chartInstance) { - initCharts(getDarkMode.value as 'default'); + initCharts(getDarkMode.value as 'default') } - return chartInstance; + return chartInstance } return { @@ -113,5 +118,5 @@ export function useECharts( resize, echarts, getInstance, - }; + } } diff --git a/src/layout/index.vue b/src/layout/index.vue index ad9b37f..f6ad211 100644 --- a/src/layout/index.vue +++ b/src/layout/index.vue @@ -1,6 +1,7 @@ +