代码规范强制使用单引号并取消行末分号

This commit is contained in:
chuzhixin 2020-10-08 13:43:57 +08:00
parent b580cd6106
commit 4a955105e9
55 changed files with 1147 additions and 1154 deletions

View File

@ -3,12 +3,12 @@ module.exports = {
env: {
node: true,
},
extends: ["plugin:vue/vue3-essential", "eslint:recommended", "@vue/prettier"],
extends: ['plugin:vue/vue3-essential', 'eslint:recommended', '@vue/prettier'],
parserOptions: {
parser: "babel-eslint",
parser: 'babel-eslint',
},
rules: {
"no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
"no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
},
};
}

View File

@ -1,3 +1,3 @@
module.exports = {
extends: ["stylelint-config-recess-order", "stylelint-config-prettier"],
};
extends: ['stylelint-config-recess-order', 'stylelint-config-prettier'],
}

View File

@ -1,3 +1,3 @@
module.exports = {
presets: ["@vue/cli-plugin-babel/preset"],
};
presets: ['@vue/cli-plugin-babel/preset'],
}

View File

@ -22,38 +22,38 @@
*/
const data = [
{
path: "/",
component: "Layout",
redirect: "/index",
path: '/',
component: 'Layout',
redirect: '/index',
meta: {
title: "首页",
icon: "home-4-line",
title: '首页',
icon: 'home-4-line',
affix: true,
},
children: [
{
path: "index",
name: "Index",
component: "@/views/index",
path: 'index',
name: 'Index',
component: '@/views/index',
meta: {
title: "首页",
icon: "home-4-line",
title: '首页',
icon: 'home-4-line',
affix: true,
},
},
],
},
];
]
module.exports = [
{
url: "/menu/navigate",
type: "get",
url: '/menu/navigate',
type: 'get',
response() {
return {
code: 200,
msg: "success",
msg: 'success',
data,
};
}
},
},
];
]

View File

@ -1,65 +1,65 @@
const { mock } = require("mockjs");
const { handleRandomImage } = require("../utils");
const List = [];
const count = 50;
const { mock } = require('mockjs')
const { handleRandomImage } = require('../utils')
const List = []
const count = 50
for (let i = 0; i < count; i++) {
List.push(
mock({
uuid: "@uuid",
id: "@id",
title: "@title(1, 2)",
description: "@csentence",
"status|1": ["published", "draft", "deleted"],
author: "@cname",
datetime: "@datetime",
pageViews: "@integer(300, 5000)",
uuid: '@uuid',
id: '@id',
title: '@title(1, 2)',
description: '@csentence',
'status|1': ['published', 'draft', 'deleted'],
author: '@cname',
datetime: '@datetime',
pageViews: '@integer(300, 5000)',
img: handleRandomImage(228, 228),
switch: "@boolean",
percent: "@integer(80,99)",
"rate|1": [1, 2, 3, 4, 5],
switch: '@boolean',
percent: '@integer(80,99)',
'rate|1': [1, 2, 3, 4, 5],
})
);
)
}
module.exports = [
{
url: "/table/getList",
type: "get",
url: '/table/getList',
type: 'get',
response(config) {
const { title, current = 1, pageSize = 10 } = config.query;
const { title, current = 1, pageSize = 10 } = config.query
let mockList = List.filter((item) => {
return !(title && item.title.indexOf(title) < 0);
});
return !(title && item.title.indexOf(title) < 0)
})
const pageList = mockList.filter(
(item, index) =>
index < pageSize * current && index >= pageSize * (current - 1)
);
)
return {
code: 200,
msg: "success",
msg: 'success',
total: mockList.length,
data: pageList,
};
}
},
},
{
url: "/table/doEdit",
type: "post",
url: '/table/doEdit',
type: 'post',
response() {
return {
code: 200,
msg: "模拟保存成功",
};
msg: '模拟保存成功',
}
},
},
{
url: "/table/doDelete",
type: "post",
url: '/table/doDelete',
type: 'post',
response() {
return {
code: 200,
msg: "模拟删除成功",
};
msg: '模拟删除成功',
}
},
},
];
]

View File

@ -1,103 +1,103 @@
const accessTokens = {
admin: "admin-accessToken",
editor: "editor-accessToken",
test: "test-accessToken",
};
admin: 'admin-accessToken',
editor: 'editor-accessToken',
test: 'test-accessToken',
}
module.exports = [
{
url: "/login",
type: "post",
url: '/login',
type: 'post',
response(config) {
const { username } = config.body;
const accessToken = accessTokens[username];
const { username } = config.body
const accessToken = accessTokens[username]
if (!accessToken) {
return {
code: 500,
msg: "帐户或密码不正确。",
};
msg: '帐户或密码不正确。',
}
}
return {
code: 200,
msg: "success",
msg: 'success',
data: { accessToken },
};
}
},
},
{
url: "/socialLogin",
type: "post",
url: '/socialLogin',
type: 'post',
response(config) {
const { code } = config.body;
const { code } = config.body
if (!code) {
return {
code: 500,
msg: "未成功获取Token。",
};
msg: '未成功获取Token。',
}
}
return {
code: 200,
msg: "success",
data: { accessToken: accessTokens["admin"] },
};
msg: 'success',
data: { accessToken: accessTokens['admin'] },
}
},
},
{
url: "/register",
type: "post",
url: '/register',
type: 'post',
response() {
return {
code: 200,
msg: "模拟注册成功",
};
msg: '模拟注册成功',
}
},
},
{
url: "/userInfo",
type: "post",
url: '/userInfo',
type: 'post',
response(config) {
const { accessToken } = config.body;
let roles = ["admin"];
let ability = ["READ"];
let username = "admin";
if ("admin-accessToken" === accessToken) {
roles = ["admin"];
ability = ["READ", "WRITE", "DELETE"];
username = "admin";
const { accessToken } = config.body
let roles = ['admin']
let ability = ['READ']
let username = 'admin'
if ('admin-accessToken' === accessToken) {
roles = ['admin']
ability = ['READ', 'WRITE', 'DELETE']
username = 'admin'
}
if ("editor-accessToken" === accessToken) {
roles = ["editor"];
ability = ["READ", "WRITE"];
username = "editor";
if ('editor-accessToken' === accessToken) {
roles = ['editor']
ability = ['READ', 'WRITE']
username = 'editor'
}
if ("test-accessToken" === accessToken) {
roles = ["admin", "editor"];
ability = ["READ"];
username = "test";
if ('test-accessToken' === accessToken) {
roles = ['admin', 'editor']
ability = ['READ']
username = 'test'
}
return {
code: 200,
msg: "success",
msg: 'success',
data: {
roles,
ability,
username,
"avatar|1": [
"https://i.gtimg.cn/club/item/face/img/2/15922_100.gif",
"https://i.gtimg.cn/club/item/face/img/8/15918_100.gif",
'avatar|1': [
'https://i.gtimg.cn/club/item/face/img/2/15922_100.gif',
'https://i.gtimg.cn/club/item/face/img/8/15918_100.gif',
],
},
};
}
},
},
{
url: "/logout",
type: "post",
url: '/logout',
type: 'post',
response() {
return {
code: 200,
msg: "success",
};
msg: 'success',
}
},
},
];
]

View File

@ -3,14 +3,14 @@
* @description 导入所有 controller 模块npm run serve时在node环境中自动输出controller文件夹下Mock接口请勿修改
*/
const { handleMockArray } = require("./utils");
const { handleMockArray } = require('./utils')
const mocks = [];
const mockArray = handleMockArray();
const mocks = []
const mockArray = handleMockArray()
mockArray.forEach((item) => {
const obj = require(item);
mocks.push(...obj);
});
const obj = require(item)
mocks.push(...obj)
})
module.exports = {
mocks,
};
}

View File

@ -1,10 +1,10 @@
const chokidar = require("chokidar");
const bodyParser = require("body-parser");
const chalk = require("chalk");
const path = require("path");
const Mock = require("mockjs");
const { baseURL } = require("../src/config");
const mockDir = path.join(process.cwd(), "mock");
const chokidar = require('chokidar')
const bodyParser = require('body-parser')
const chalk = require('chalk')
const path = require('path')
const Mock = require('mockjs')
const { baseURL } = require('../src/config')
const mockDir = path.join(process.cwd(), 'mock')
/**
*
@ -12,21 +12,21 @@ const mockDir = path.join(process.cwd(), "mock");
* @returns {{mockStartIndex: number, mockRoutesLength: number}}
*/
const registerRoutes = (app) => {
let mockLastIndex;
const { mocks } = require("./index.js");
let mockLastIndex
const { mocks } = require('./index.js')
const mocksForServer = mocks.map((route) => {
return responseFake(route.url, route.type, route.response);
});
return responseFake(route.url, route.type, route.response)
})
for (const mock of mocksForServer) {
app[mock.type](mock.url, mock.response);
mockLastIndex = app._router.stack.length;
app[mock.type](mock.url, mock.response)
mockLastIndex = app._router.stack.length
}
const mockRoutesLength = Object.keys(mocksForServer).length;
const mockRoutesLength = Object.keys(mocksForServer).length
return {
mockRoutesLength: mockRoutesLength,
mockStartIndex: mockLastIndex - mockRoutesLength,
};
};
}
}
/**
*
@ -38,57 +38,57 @@ const registerRoutes = (app) => {
const responseFake = (url, type, respond) => {
return {
url: new RegExp(`${baseURL}${url}`),
type: type || "get",
type: type || 'get',
response(req, res) {
res.status(200);
if (JSON.stringify(req.body) !== "{}") {
console.log(chalk.green(`> 请求地址:${req.path}`));
console.log(chalk.green(`> 请求参数:${JSON.stringify(req.body)}\n`));
res.status(200)
if (JSON.stringify(req.body) !== '{}') {
console.log(chalk.green(`> 请求地址:${req.path}`))
console.log(chalk.green(`> 请求参数:${JSON.stringify(req.body)}\n`))
} else {
console.log(chalk.green(`> 请求地址:${req.path}\n`));
console.log(chalk.green(`> 请求地址:${req.path}\n`))
}
res.json(
Mock.mock(respond instanceof Function ? respond(req, res) : respond)
);
)
},
};
};
}
}
/**
*
* @param app
*/
module.exports = (app) => {
app.use(bodyParser.json());
app.use(bodyParser.json())
app.use(
bodyParser.urlencoded({
extended: true,
})
);
)
const mockRoutes = registerRoutes(app);
let mockRoutesLength = mockRoutes.mockRoutesLength;
let mockStartIndex = mockRoutes.mockStartIndex;
const mockRoutes = registerRoutes(app)
let mockRoutesLength = mockRoutes.mockRoutesLength
let mockStartIndex = mockRoutes.mockStartIndex
chokidar
.watch(mockDir, {
ignored: /mock-server/,
ignoreInitial: true,
})
.on("all", (event) => {
if (event === "change" || event === "add") {
.on('all', (event) => {
if (event === 'change' || event === 'add') {
try {
app._router.stack.splice(mockStartIndex, mockRoutesLength);
app._router.stack.splice(mockStartIndex, mockRoutesLength)
Object.keys(require.cache).forEach((item) => {
if (item.includes(mockDir)) {
delete require.cache[require.resolve(item)];
delete require.cache[require.resolve(item)]
}
});
const mockRoutes = registerRoutes(app);
mockRoutesLength = mockRoutes.mockRoutesLength;
mockStartIndex = mockRoutes.mockStartIndex;
})
const mockRoutes = registerRoutes(app)
mockRoutesLength = mockRoutes.mockRoutesLength
mockStartIndex = mockRoutes.mockStartIndex
} catch (error) {
console.log(chalk.red(error));
console.log(chalk.red(error))
}
}
});
};
})
}

View File

@ -1,6 +1,6 @@
const { Random } = require("mockjs");
const { join } = require("path");
const fs = require("fs");
const { Random } = require('mockjs')
const { join } = require('path')
const fs = require('fs')
/**
* @author chuzhixin 1204505056@qq.com
@ -10,7 +10,7 @@ const fs = require("fs");
* @returns {string}
*/
function handleRandomImage(width = 50, height = 50) {
return `https://picsum.photos/${width}/${height}?random=${Random.guid()}`;
return `https://picsum.photos/${width}/${height}?random=${Random.guid()}`
}
/**
@ -19,25 +19,25 @@ function handleRandomImage(width = 50, height = 50) {
* @returns {[]}
*/
function handleMockArray() {
const mockArray = [];
const mockArray = []
const getFiles = (jsonPath) => {
const jsonFiles = [];
const jsonFiles = []
const findJsonFile = (path) => {
const files = fs.readdirSync(path);
const files = fs.readdirSync(path)
files.forEach((item) => {
const fPath = join(path, item);
const stat = fs.statSync(fPath);
if (stat.isDirectory() === true) findJsonFile(item);
if (stat.isFile() === true) jsonFiles.push(item);
});
};
findJsonFile(jsonPath);
jsonFiles.forEach((item) => mockArray.push(`./controller/${item}`));
};
getFiles("mock/controller");
return mockArray;
const fPath = join(path, item)
const stat = fs.statSync(fPath)
if (stat.isDirectory() === true) findJsonFile(item)
if (stat.isFile() === true) jsonFiles.push(item)
})
}
findJsonFile(jsonPath)
jsonFiles.forEach((item) => mockArray.push(`./controller/${item}`))
}
getFiles('mock/controller')
return mockArray
}
module.exports = {
handleRandomImage,
handleMockArray,
};
}

View File

@ -2,15 +2,15 @@ module.exports = {
printWidth: 80,
tabWidth: 2,
useTabs: false,
semi: true,
singleQuote: false,
quoteProps: "as-needed",
semi: false,
singleQuote: true,
quoteProps: 'as-needed',
jsxSingleQuote: false,
trailingComma: "es5",
trailingComma: 'es5',
bracketSpacing: true,
jsxBracketSameLine: false,
arrowParens: "always",
htmlWhitespaceSensitivity: "ignore",
arrowParens: 'always',
htmlWhitespaceSensitivity: 'ignore',
vueIndentScriptAndStyle: true,
endOfLine: "lf",
};
endOfLine: 'lf',
}

View File

@ -2,5 +2,5 @@
<router-view />
</template>
<style lang="less">
@import "~@/vab/styles/vab.less";
@import '~@/vab/styles/vab.less';
</style>

View File

@ -1,9 +1,9 @@
import request from "@/utils/request";
import request from '@/utils/request'
export function getRouterList(params) {
return request({
url: "/menu/navigate",
method: "get",
url: '/menu/navigate',
method: 'get',
params,
});
})
}

View File

@ -1,25 +1,25 @@
import request from "@/utils/request";
import request from '@/utils/request'
export function getList(params) {
return request({
url: "/table/getList",
method: "get",
url: '/table/getList',
method: 'get',
params,
});
})
}
export function doEdit(data) {
return request({
url: "/table/doEdit",
method: "post",
url: '/table/doEdit',
method: 'post',
data,
});
})
}
export function doDelete(data) {
return request({
url: "/table/doDelete",
method: "post",
url: '/table/doDelete',
method: 'post',
data,
});
})
}

View File

@ -1,43 +1,43 @@
import request from "@/utils/request";
import { tokenName } from "@/config";
import request from '@/utils/request'
import { tokenName } from '@/config'
export async function login(data) {
return request({
url: "/login",
method: "post",
url: '/login',
method: 'post',
data,
});
})
}
export async function socialLogin(data) {
return request({
url: "/socialLogin",
method: "post",
url: '/socialLogin',
method: 'post',
data,
});
})
}
export function getUserInfo(accessToken) {
//此处为了兼容mock.js使用data传递accessToken如果使用mock可以走headers
return request({
url: "/userInfo",
method: "post",
url: '/userInfo',
method: 'post',
data: {
[tokenName]: accessToken,
},
});
})
}
export function logout() {
return request({
url: "/logout",
method: "post",
});
url: '/logout',
method: 'post',
})
}
export function register() {
return request({
url: "/register",
method: "post",
});
url: '/register',
method: 'post',
})
}

View File

@ -2,8 +2,8 @@
* @description 导出自定义配置
**/
const config = {
layout: "vertical",
layout: 'vertical',
donation: true,
templateFolder: "project",
};
module.exports = config;
templateFolder: 'project',
}
module.exports = config

View File

@ -1,8 +1,8 @@
/**
* @description 导出默认配置(通用配置|主题配置|网络配置)
**/
const setting = require("./setting.config");
const theme = require("./theme.config");
const network = require("./net.config");
const setting = require('./setting.config')
const theme = require('./theme.config')
const network = require('./net.config')
module.exports = { setting, theme, network };
module.exports = { setting, theme, network }

View File

@ -3,12 +3,12 @@
**/
const network = {
//配后端数据的接收方式application/json;charset=UTF-8 或 application/x-www-form-urlencoded;charset=UTF-8
contentType: "application/json;charset=UTF-8",
contentType: 'application/json;charset=UTF-8',
//消息框消失时间
messageDuration: 3000,
//最长请求时间
requestTimeout: 10000,
//操作正常code支持String、Array、int多种类型
successCode: [200, 0],
};
module.exports = network;
}
module.exports = network

View File

@ -3,77 +3,77 @@
*/
const setting = {
//开发以及部署时的URLhash模式时在不确定二级目录名称的情况下建议使用""代表相对路径或者"/二级目录/"history模式默认使用"/"或者"/二级目录/"
publicPath: "",
publicPath: '',
//生产环境构建文件的目录名
outputDir: "dist",
outputDir: 'dist',
//放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录。
assetsDir: "static",
assetsDir: 'static',
//开发环境每次保存时是否输出为eslint编译警告
lintOnSave: true,
//进行编译的依赖
transpileDependencies: ["vue-echarts", "resize-detector"],
transpileDependencies: ['vue-echarts', 'resize-detector'],
//默认的接口地址 如果是开发环境和生产环境走vab-mock-server当然你也可以选择自己配置成需要的接口地址
baseURL:
process.env.NODE_ENV === "development" ? "mock-server" : "mock-server",
process.env.NODE_ENV === 'development' ? 'mock-server' : 'mock-server',
//标题 (包括初次加载雪花屏的标题 页面的标题 浏览器的标题)
title: "vue-admin-beautiful-antdv",
title: 'vue-admin-beautiful-antdv',
//标题分隔符
titleSeparator: " - ",
titleSeparator: ' - ',
//标题是否反转 如果为false:"page - title"如果为ture:"title - page"
titleReverse: false,
//简写
abbreviation: "vab-pro",
abbreviation: 'vab-pro',
//开发环境端口号
devPort: "9999",
devPort: '9999',
//版本号
version: process.env.VUE_APP_VERSION,
//pro版本copyright可随意修改
copyright: "chuzhixin 1204505056@qq.com",
copyright: 'chuzhixin 1204505056@qq.com',
//缓存路由的最大数量
keepAliveMaxNum: 99,
//路由模式,可选值为 history 或 hash
routerMode: "hash",
routerMode: 'hash',
//不经过token校验的路由
routesWhiteList: ["/login", "/register", "/callback", "/404", "/403"],
routesWhiteList: ['/login', '/register', '/callback', '/404', '/403'],
//加载时显示文字
loadingText: "正在加载中...",
loadingText: '正在加载中...',
//token名称
tokenName: "accessToken",
tokenName: 'accessToken',
//token在localStorage、sessionStorage、cookie存储的key的名称
tokenTableName: "accessToken",
tokenTableName: 'accessToken',
//token存储位置localStorage sessionStorage cookie
storage: "localStorage",
storage: 'localStorage',
//token失效回退到登录页时是否记录本次的路由
recordRoute: true,
//是否显示logo不显示时设置false显示时请填写remixIcon图标名称暂时只支持设置remixIcon
logo: "vuejs-fill",
logo: 'vuejs-fill',
//语言类型zh、en
i18n: "zh",
i18n: 'zh',
//在哪些环境下显示高亮错误
errorLog: ["development", "production"],
errorLog: ['development', 'production'],
//是否开启登录拦截
loginInterception: true,
//是否开启登录RSA加密
loginRSA: false,
//intelligence前端导出路由和all后端导出路由两种方式
authentication: "intelligence",
authentication: 'intelligence',
//是否开启roles字段进行角色权限控制如果是all模式后端完全处理角色并进行json组装可设置false不处理路由中的roles字段
rolesControl: true,
//vertical gallery comprehensive common布局时是否只保持一个子菜单的展开
uniqueOpened: false,
//vertical布局时默认展开的菜单path使用逗号隔开建议只展开一个
defaultOpeneds: ["/vab"],
defaultOpeneds: ['/vab'],
//需要加loading层的请求防止重复提交
debounce: ["doEdit"],
debounce: ['doEdit'],
//需要自动注入并加载的模块
providePlugin: {},
//npm run build时是否自动生成7z压缩包
build7z: false,
//代码生成机生成在view下的文件夹名称
templateFolder: "project",
templateFolder: 'project',
//是否显示终端donation打印
donation: false,
//画廊布局和综合布局时,是否点击一级菜单默认开启第一个二级菜单
openFirstMenu: true,
};
module.exports = setting;
}
module.exports = setting

View File

@ -3,9 +3,9 @@
*/
const theme = {
//布局种类 horizontal vertical gallery comprehensive common
layout: "horizontal",
layout: 'horizontal',
//主题名称 default ocean green glory white
themeName: "default",
themeName: 'default',
//是否固定头部
fixedHeader: true,
//是否显示顶部进度条
@ -24,5 +24,5 @@ const theme = {
showNotice: true,
//是否显示全屏组件
showFullScreen: true,
};
module.exports = theme;
}
module.exports = theme

View File

@ -2,8 +2,8 @@
* @description 3个子配置通用配置|主题配置|网络配置建议在当前目录下修改config.js修改配置会覆盖默认配置也可以直接修改默认配置
*/
//默认配置
const { setting, theme, network } = require("./default");
const { setting, theme, network } = require('./default')
//自定义配置
const config = require("./config");
const config = require('./config')
//导出配置(以自定义配置为主)
module.exports = Object.assign({}, setting, theme, network, config);
module.exports = Object.assign({}, setting, theme, network, config)

View File

@ -48,13 +48,13 @@
</a-layout>
</template>
<script>
import VabLogo from "./vab-logo";
import VabAvatar from "./vab-avatar";
import VabMenu from "./vab-menu";
import VabTabs from "./vab-tabs";
import VabContent from "./vab-content";
import { mapActions, mapGetters } from "vuex";
import { MenuUnfoldOutlined, MenuFoldOutlined } from "@ant-design/icons-vue";
import VabLogo from './vab-logo'
import VabAvatar from './vab-avatar'
import VabMenu from './vab-menu'
import VabTabs from './vab-tabs'
import VabContent from './vab-content'
import { mapActions, mapGetters } from 'vuex'
import { MenuUnfoldOutlined, MenuFoldOutlined } from '@ant-design/icons-vue'
export default {
components: {
@ -68,58 +68,58 @@
},
data() {
return {
selectedKeys: ["/index"],
};
selectedKeys: ['/index'],
}
},
computed: {
...mapGetters({
collapse: "settings/collapse",
routes: "routes/routes",
device: "settings/device",
collapse: 'settings/collapse',
routes: 'routes/routes',
device: 'settings/device',
}),
classObj() {
return {
"vab-mobile": this.device === "mobile",
"vab-collapse": this.collapse,
};
'vab-mobile': this.device === 'mobile',
'vab-collapse': this.collapse,
}
},
},
watch: {
$route: {
handler({ fullPath }) {
//
if (fullPath === "/index") fullPath = "/";
if (fullPath === "/test/test") fullPath = "/test";
this.selectedKeys = [fullPath];
if (fullPath === '/index') fullPath = '/'
if (fullPath === '/test/test') fullPath = '/test'
this.selectedKeys = [fullPath]
},
immediate: true,
},
},
beforeMount() {
window.addEventListener("resize", this.handleLayouts);
window.addEventListener('resize', this.handleLayouts)
},
beforeUnmount() {
window.removeEventListener("resize", this.handleLayouts);
window.removeEventListener('resize', this.handleLayouts)
},
mounted() {
this.handleLayouts();
this.handleLayouts()
},
methods: {
...mapActions({
toggleDevice: "settings/toggleDevice",
handleFoldSideBar: "settings/foldSideBar",
toggleCollapse: "settings/toggleCollapse",
toggleDevice: 'settings/toggleDevice',
handleFoldSideBar: 'settings/foldSideBar',
toggleCollapse: 'settings/toggleCollapse',
}),
handleLayouts() {
const width = document.body.getBoundingClientRect().width;
const width = document.body.getBoundingClientRect().width
if (this.width !== width) {
const isMobile = width - 1 < 992;
this.toggleDevice(isMobile ? "mobile" : "desktop");
this.width = width;
const isMobile = width - 1 < 992
this.toggleDevice(isMobile ? 'mobile' : 'desktop')
this.width = width
}
},
},
};
}
</script>
<style lang="less">
.ant-layout-content {

View File

@ -16,31 +16,31 @@
</template>
<script>
import { recordRoute } from "@/config";
import { DownOutlined } from "@ant-design/icons-vue";
import { recordRoute } from '@/config'
import { DownOutlined } from '@ant-design/icons-vue'
import { mapGetters } from "vuex";
import { mapGetters } from 'vuex'
export default {
name: "VabAvatar",
name: 'VabAvatar',
components: { DownOutlined },
computed: {
...mapGetters({
avatar: "user/avatar",
username: "user/username",
avatar: 'user/avatar',
username: 'user/username',
}),
},
methods: {
async logout() {
await this.$store.dispatch("user/logout");
await this.$store.dispatch('user/logout')
if (recordRoute) {
const fullPath = this.$route.fullPath;
this.$router.push(`/login?redirect=${fullPath}`);
const fullPath = this.$route.fullPath
this.$router.push(`/login?redirect=${fullPath}`)
} else {
this.$router.push("/login");
this.$router.push('/login')
}
},
},
};
}
</script>
<style lang="less">
.vab-avatar {

View File

@ -10,18 +10,18 @@
<script>
export default {
name: "VabContent",
name: 'VabContent',
watch: {
$route: {
handler() {
if ("mobile" === this.device) {
this.$store.dispatch("settings/foldSideBar");
if ('mobile' === this.device) {
this.$store.dispatch('settings/foldSideBar')
}
},
immediate: true,
},
},
};
}
</script>
<style lang="less">

View File

@ -3,21 +3,21 @@
</template>
<script>
import "remixicon/fonts/remixicon.css";
import 'remixicon/fonts/remixicon.css'
export default {
name: "VabIcon",
name: 'VabIcon',
props: {
icon: {
type: String,
required: true,
},
},
};
}
</script>
<style lang="less" scoped>
[class*="ri"] {
[class*='ri'] {
font-size: 16px;
vertical-align: -1px;
}

View File

@ -7,18 +7,18 @@
</template>
<script>
import VabIcon from "@/layout/vab-icon";
import { mapGetters } from "vuex";
import VabIcon from '@/layout/vab-icon'
import { mapGetters } from 'vuex'
export default {
name: "VabLogo",
name: 'VabLogo',
components: { VabIcon },
computed: {
...mapGetters({
logo: "settings/logo",
title: "settings/title",
logo: 'settings/logo',
title: 'settings/title',
}),
},
};
}
</script>
<style lang="less" scoped>
.vab-logo {

View File

@ -8,16 +8,16 @@
</template>
<script>
import { isExternal } from "@/utils/validate";
import VabIcon from "@/layout/vab-icon";
import { isExternal } from '@/utils/validate'
import VabIcon from '@/layout/vab-icon'
export default {
name: "MenuItem",
name: 'MenuItem',
components: { VabIcon },
props: {
item: {
type: Object,
default() {
return null;
return null
},
},
routeChildren: {
@ -27,16 +27,16 @@
},
methods: {
handleLink() {
const routePath = this.routeChildren.fullPath;
const target = this.routeChildren.meta.target;
if (target === "_blank") {
if (isExternal(routePath)) window.open(routePath);
else if (this.$route.path !== routePath) window.open(routePath.href);
const routePath = this.routeChildren.fullPath
const target = this.routeChildren.meta.target
if (target === '_blank') {
if (isExternal(routePath)) window.open(routePath)
else if (this.$route.path !== routePath) window.open(routePath.href)
} else {
if (isExternal(routePath)) window.location.href = routePath;
else if (this.$route.path !== routePath) this.$router.push(routePath);
if (isExternal(routePath)) window.location.href = routePath
else if (this.$route.path !== routePath) this.$router.push(routePath)
}
},
},
};
}
</script>

View File

@ -11,24 +11,24 @@
</template>
<script>
import VabIcon from "@/layout/vab-icon";
import VabIcon from '@/layout/vab-icon'
export default {
name: "Submenu",
name: 'Submenu',
components: { VabIcon },
props: {
item: {
type: Object,
default() {
return null;
return null
},
},
routeChildren: {
type: Object,
default() {
return null;
return null
},
},
},
methods: {},
};
}
</script>

View File

@ -16,10 +16,10 @@
</template>
<script>
import MenuItem from "./components/MenuItem";
import Submenu from "./components/Submenu";
import MenuItem from './components/MenuItem'
import Submenu from './components/Submenu'
export default {
name: "VabMenu",
name: 'VabMenu',
components: { MenuItem, Submenu },
props: {
item: {
@ -30,28 +30,28 @@
data() {
return {
routeChildren: {},
menuComponent: "",
};
menuComponent: '',
}
},
created() {
const showChildren = this.handleChildren(this.item.children);
const showChildren = this.handleChildren(this.item.children)
if (showChildren.length === 0) {
this.menuComponent = "MenuItem";
this.routeChildren = this.item;
this.menuComponent = 'MenuItem'
this.routeChildren = this.item
} else if (showChildren.length === 1 && this.item.alwaysShow !== true) {
this.menuComponent = "MenuItem";
this.routeChildren = showChildren[0];
this.menuComponent = 'MenuItem'
this.routeChildren = showChildren[0]
} else {
this.menuComponent = "Submenu";
this.menuComponent = 'Submenu'
}
},
methods: {
handleChildren(children = []) {
if (children === null) return [];
return children.filter((item) => item.hidden !== true);
if (children === null) return []
return children.filter((item) => item.hidden !== true)
},
},
};
}
</script>
<style lang="less">
.anticon {

View File

@ -44,10 +44,10 @@
</template>
<script>
import { DownOutlined } from "@ant-design/icons-vue";
import { mapActions, mapGetters } from "vuex";
import { DownOutlined } from '@ant-design/icons-vue'
import { mapActions, mapGetters } from 'vuex'
export default {
name: "VabTabs",
name: 'VabTabs',
components: {
DownOutlined,
},
@ -56,44 +56,44 @@
affixTabs: [],
tabActive: null,
created: false,
};
}
},
computed: {
...mapGetters({
visitedRoutes: "tagsBar/visitedRoutes",
routes: "routes/routes",
visitedRoutes: 'tagsBar/visitedRoutes',
routes: 'routes/routes',
}),
},
watch: {
$route: {
handler(route) {
this.addTabs(route);
this.addTabs(route)
},
},
},
created() {
this.initAffixTabs(this.routes);
this.addTabs(this.$route);
this.initAffixTabs(this.routes)
this.addTabs(this.$route)
},
methods: {
...mapActions({
addVisitedRoute: "tagsBar/addVisitedRoute",
delVisitedRoute: "tagsBar/delVisitedRoute",
delOthersVisitedRoutes: "tagsBar/delOthersVisitedRoutes",
delLeftVisitedRoutes: "tagsBar/delLeftVisitedRoutes",
delRightVisitedRoutes: "tagsBar/delRightVisitedRoutes",
delAllVisitedRoutes: "tagsBar/delAllVisitedRoutes",
addVisitedRoute: 'tagsBar/addVisitedRoute',
delVisitedRoute: 'tagsBar/delVisitedRoute',
delOthersVisitedRoutes: 'tagsBar/delOthersVisitedRoutes',
delLeftVisitedRoutes: 'tagsBar/delLeftVisitedRoutes',
delRightVisitedRoutes: 'tagsBar/delRightVisitedRoutes',
delAllVisitedRoutes: 'tagsBar/delAllVisitedRoutes',
}),
initAffixTabs(routes) {
routes.forEach((route) => {
if (route.meta && route.meta.affix) this.addTabs(route);
if (route.children) this.initAffixTabs(route.children);
});
if (route.meta && route.meta.affix) this.addTabs(route)
if (route.children) this.initAffixTabs(route.children)
})
},
async addTabs(tag) {
if (tag.name && tag.meta && tag.meta.tagHidden !== true) {
let matched = [tag.name];
if (tag.matched) matched = tag.matched.map((item) => item.name);
let matched = [tag.name]
if (tag.matched) matched = tag.matched.map((item) => item.name)
await this.addVisitedRoute({
path: tag.path,
fullPath: tag.fullPath,
@ -101,78 +101,78 @@
name: tag.name,
matched: matched,
meta: { ...tag.meta },
});
this.tabActive = tag.fullPath;
})
this.tabActive = tag.fullPath
}
},
isActive(route) {
return route.path === this.$route.path;
return route.path === this.$route.path
},
isAffix(tag) {
return tag.meta && tag.meta.affix;
return tag.meta && tag.meta.affix
},
handleTabClick(tab) {
const route = this.visitedRoutes.filter((item) => item.path === tab)[0];
if (this.$route.fullPath !== route.fullPath) this.$router.push(route);
const route = this.visitedRoutes.filter((item) => item.path === tab)[0]
if (this.$route.fullPath !== route.fullPath) this.$router.push(route)
},
async handleTabRemove(fullPath) {
const view = this.visitedRoutes.find((item) => {
return fullPath === item.fullPath;
});
await this.delVisitedRoute(view);
if (this.isActive(view)) this.toLastTag();
return fullPath === item.fullPath
})
await this.delVisitedRoute(view)
if (this.isActive(view)) this.toLastTag()
},
handleClick({ key }) {
switch (key) {
case "closeOthersTabs":
this.closeOthersTabs();
break;
case "closeLeftTabs":
this.closeLeftTabs();
break;
case "closeRightTabs":
this.closeRightTabs();
break;
case "closeAllTabs":
this.closeAllTabs();
break;
case 'closeOthersTabs':
this.closeOthersTabs()
break
case 'closeLeftTabs':
this.closeLeftTabs()
break
case 'closeRightTabs':
this.closeRightTabs()
break
case 'closeAllTabs':
this.closeAllTabs()
break
}
},
async closeSelectedTag(view) {
await this.delVisitedRoute(view);
await this.delVisitedRoute(view)
if (this.isActive(view)) {
this.toLastTag();
this.toLastTag()
}
},
async closeOthersTabs() {
await this.delOthersVisitedRoutes(this.toThisTag());
await this.delOthersVisitedRoutes(this.toThisTag())
},
async closeLeftTabs() {
await this.delLeftVisitedRoutes(this.toThisTag());
await this.delLeftVisitedRoutes(this.toThisTag())
},
async closeRightTabs() {
await this.delRightVisitedRoutes(this.toThisTag());
await this.delRightVisitedRoutes(this.toThisTag())
},
async closeAllTabs() {
await this.delAllVisitedRoutes();
await this.delAllVisitedRoutes()
if (this.affixTabs.some((tag) => tag.path === this.toThisTag().path))
return;
this.toLastTag();
return
this.toLastTag()
},
toLastTag() {
const latestView = this.visitedRoutes.slice(-1)[0];
if (latestView) this.$router.push(latestView);
else this.$router.push("/");
const latestView = this.visitedRoutes.slice(-1)[0]
if (latestView) this.$router.push(latestView)
else this.$router.push('/')
},
toThisTag() {
const view = this.visitedRoutes.find(
(item) => item.fullPath === this.$route.fullPath
);
if (this.$route.path !== view.path) this.$router.push(view);
return view;
)
if (this.$route.path !== view.path) this.$router.push(view)
return view
},
},
};
}
</script>
<style lang="less">
.vab-tabs {

View File

@ -1,17 +1,17 @@
import { createApp } from "vue";
import Antd from "ant-design-vue";
import App from "./App";
import router from "./router";
import store from "./store";
import "ant-design-vue/dist/antd.css";
import "@/vab";
import { createApp } from 'vue'
import Antd from 'ant-design-vue'
import App from './App'
import router from './router'
import store from './store'
import 'ant-design-vue/dist/antd.css'
import '@/vab'
/**
* @author chuzhixin 1204505056@qq.com
* @description 正式环境默认使用mock正式项目记得注释后再打包
*/
if (process.env.NODE_ENV === "production") {
const { mockXHR } = require("@/utils/static");
mockXHR();
if (process.env.NODE_ENV === 'production') {
const { mockXHR } = require('@/utils/static')
mockXHR()
}
createApp(App).use(store).use(router).use(Antd).mount("#app");
createApp(App).use(store).use(router).use(Antd).mount('#app')

View File

@ -1,128 +1,128 @@
import { createRouter, createWebHashHistory } from "vue-router";
import Layout from "@/layout";
import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '@/layout'
export const constantRoutes = [
{
path: "/login",
component: () => import("@/views/login"),
path: '/login',
component: () => import('@/views/login'),
hidden: true,
},
{
path: "/403",
name: "403",
component: () => import("@/views/403"),
path: '/403',
name: '403',
component: () => import('@/views/403'),
hidden: true,
},
{
path: "/404",
name: "404",
component: () => import("@/views/404"),
path: '/404',
name: '404',
component: () => import('@/views/404'),
hidden: true,
},
];
]
export const asyncRoutes = [
{
path: "/",
path: '/',
component: Layout,
redirect: "/index",
redirect: '/index',
meta: {
title: "首页",
icon: "home-4-line",
title: '首页',
icon: 'home-4-line',
affix: true,
},
children: [
{
path: "index",
name: "Index",
component: () => import("@/views/index"),
path: 'index',
name: 'Index',
component: () => import('@/views/index'),
meta: {
title: "首页",
icon: "home-4-line",
title: '首页',
icon: 'home-4-line',
affix: true,
},
},
],
},
{
path: "/vab",
path: '/vab',
component: Layout,
redirect: "/vab/table",
redirect: '/vab/table',
alwaysShow: true,
meta: {
title: "组件",
icon: "apps-line",
title: '组件',
icon: 'apps-line',
},
children: [
{
path: "table",
name: "Table",
component: () => import("@/views/vab/table"),
path: 'table',
name: 'Table',
component: () => import('@/views/vab/table'),
meta: {
title: "表格",
icon: "table-2",
title: '表格',
icon: 'table-2',
},
},
],
},
{
path: "/test",
path: '/test',
component: Layout,
redirect: "/test/test",
redirect: '/test/test',
meta: {
title: "动态路由测试",
icon: "test-tube-line",
title: '动态路由测试',
icon: 'test-tube-line',
},
children: [
{
path: "test",
name: "Test",
component: () => import("@/views/test"),
path: 'test',
name: 'Test',
component: () => import('@/views/test'),
meta: {
title: "动态路由测试",
icon: "test-tube-line",
title: '动态路由测试',
icon: 'test-tube-line',
},
},
],
},
{
path: "/error",
name: "Error",
path: '/error',
name: 'Error',
component: Layout,
redirect: "/error/403",
redirect: '/error/403',
meta: {
title: "错误页",
icon: "error-warning-line",
title: '错误页',
icon: 'error-warning-line',
},
children: [
{
path: "403",
name: "Error403",
component: () => import("@/views/403"),
path: '403',
name: 'Error403',
component: () => import('@/views/403'),
meta: {
title: "403",
icon: "error-warning-line",
title: '403',
icon: 'error-warning-line',
},
},
{
path: "404",
name: "Error404",
component: () => import("@/views/404"),
path: '404',
name: 'Error404',
component: () => import('@/views/404'),
meta: {
title: "404",
icon: "error-warning-line",
title: '404',
icon: 'error-warning-line',
},
},
],
},
{
path: "/*",
redirect: "/404",
path: '/*',
redirect: '/404',
hidden: true,
},
];
]
const router = createRouter({
history: createWebHashHistory(),
routes: constantRoutes,
});
})
export default router;
export default router

View File

@ -2,16 +2,16 @@
* @author chuzhixin 1204505056@qq.com
* @description 导入所有 vuex 模块自动加入namespaced:true用于解决vuex命名冲突请勿修改
*/
import { createStore } from "vuex";
import { createStore } from 'vuex'
const files = require.context("./modules", false, /\.js$/);
const modules = {};
const files = require.context('./modules', false, /\.js$/)
const modules = {}
files.keys().forEach((key) => {
modules[key.replace(/(\.\/|\.js)/g, "")] = files(key).default;
});
modules[key.replace(/(\.\/|\.js)/g, '')] = files(key).default
})
Object.keys(modules).forEach((key) => {
modules[key]["namespaced"] = true;
});
modules[key]['namespaced'] = true
})
export default createStore({
modules,
});
})

View File

@ -2,32 +2,32 @@ const state = {
admin: false,
role: [],
ability: [],
};
}
const getters = {
admin: (state) => state.admin,
role: (state) => state.role,
ability: (state) => state.ability,
};
}
const mutations = {
setFull(state, admin) {
state.admin = admin;
state.admin = admin
},
setRole(state, role) {
state.role = role;
state.role = role
},
setAbility(state, ability) {
state.ability = ability;
state.ability = ability
},
};
}
const actions = {
setFull({ commit }, admin) {
commit("setFull", admin);
commit('setFull', admin)
},
setRole({ commit }, role) {
commit("setRole", role);
commit('setRole', role)
},
setAbility({ commit }, ability) {
commit("setAbility", ability);
commit('setAbility', ability)
},
};
export default { state, getters, mutations, actions };
}
export default { state, getters, mutations, actions }

View File

@ -2,23 +2,23 @@
* @author chuzhixin 1204505056@qq.com
* @description 路由拦截状态管理目前两种模式all模式与intelligence模式其中partialRoutes是菜单暂未使用
*/
import { asyncRoutes, constantRoutes } from "@/router";
import { getRouterList } from "@/api/router";
import { convertRouter, filterRoutes } from "@/utils/routes";
import { asyncRoutes, constantRoutes } from '@/router'
import { getRouterList } from '@/api/router'
import { convertRouter, filterRoutes } from '@/utils/routes'
const state = { routes: [], partialRoutes: [] };
const state = { routes: [], partialRoutes: [] }
const getters = {
routes: (state) => state.routes,
partialRoutes: (state) => state.partialRoutes,
};
}
const mutations = {
setRoutes(state, routes) {
state.routes = routes;
state.routes = routes
},
setPartialRoutes(state, routes) {
state.partialRoutes = routes;
state.partialRoutes = routes
},
};
}
const actions = {
/**
* @author chuzhixin 1204505056@qq.com
@ -27,9 +27,9 @@ const actions = {
* @returns
*/
async setRoutes({ commit }) {
const finallyRoutes = filterRoutes([...constantRoutes, ...asyncRoutes]);
commit("setRoutes", finallyRoutes);
return [...asyncRoutes];
const finallyRoutes = filterRoutes([...constantRoutes, ...asyncRoutes])
commit('setRoutes', finallyRoutes)
return [...asyncRoutes]
},
/**
* @author chuzhixin 1204505056@qq.com
@ -38,13 +38,13 @@ const actions = {
* @returns
*/
async setAllRoutes({ commit }) {
let { data } = await getRouterList();
if (data[data.length - 1].path !== "*")
data.push({ path: "*", redirect: "/404", hidden: true });
const asyncRoutes = convertRouter(data);
const finallyRoutes = filterRoutes([...constantRoutes, ...asyncRoutes]);
commit("setRoutes", finallyRoutes);
return [...asyncRoutes];
let { data } = await getRouterList()
if (data[data.length - 1].path !== '*')
data.push({ path: '*', redirect: '/404', hidden: true })
const asyncRoutes = convertRouter(data)
const finallyRoutes = filterRoutes([...constantRoutes, ...asyncRoutes])
commit('setRoutes', finallyRoutes)
return [...asyncRoutes]
},
/**
* @author chuzhixin 1204505056@qq.com
@ -53,7 +53,7 @@ const actions = {
* @param accessedRoutes 画廊布局综合布局设置路由
*/
setPartialRoutes({ commit }, accessedRoutes) {
commit("setPartialRoutes", accessedRoutes);
commit('setPartialRoutes', accessedRoutes)
},
};
export default { state, getters, mutations, actions };
}
export default { state, getters, mutations, actions }

View File

@ -2,8 +2,8 @@
* @author chuzhixin 1204505056@qq.com
* @description 所有全局配置的状态管理如无必要请勿修改
*/
import defaultSettings from "@/config";
import { isJson } from "@/utils/validate";
import defaultSettings from '@/config'
import { isJson } from '@/utils/validate'
const {
logo,
@ -20,23 +20,23 @@ const {
showTagsBar,
showNotice,
showFullScreen,
} = defaultSettings;
} = defaultSettings
const getLocalStorage = (key) => {
const value = localStorage.getItem(key);
const value = localStorage.getItem(key)
if (isJson(value)) {
return JSON.parse(value);
return JSON.parse(value)
} else {
return false;
return false
}
};
}
const theme = getLocalStorage("vue-admin-beautiful-pro-theme");
const { collapse } = getLocalStorage("vue-admin-beautiful-pro-collapse");
const { language } = getLocalStorage("vue-admin-beautiful-pro-language");
const theme = getLocalStorage('vue-admin-beautiful-pro-theme')
const { collapse } = getLocalStorage('vue-admin-beautiful-pro-collapse')
const { language } = getLocalStorage('vue-admin-beautiful-pro-language')
const toggleBoolean = (key) => {
return typeof theme[key] !== "undefined" ? theme[key] : key;
};
return typeof theme[key] !== 'undefined' ? theme[key] : key
}
const state = {
logo,
@ -45,7 +45,7 @@ const state = {
themeName: theme.themeName || themeName,
layout: theme.layout || layout,
header: theme.header || header,
device: "desktop",
device: 'desktop',
language: language || i18n,
showLanguage: toggleBoolean(showLanguage),
showProgressBar: toggleBoolean(showProgressBar),
@ -55,7 +55,7 @@ const state = {
showTagsBar: toggleBoolean(showTagsBar),
showNotice: toggleBoolean(showNotice),
showFullScreen: toggleBoolean(showFullScreen),
};
}
const getters = {
collapse: (state) => state.collapse,
device: (state) => state.device,
@ -73,107 +73,107 @@ const getters = {
showNotice: (state) => state.showNotice,
showFullScreen: (state) => state.showFullScreen,
themeName: (state) => state.themeName,
};
}
const mutations = {
toggleCollapse(state) {
state.collapse = !state.collapse;
state.collapse = !state.collapse
localStorage.setItem(
"vue-admin-beautiful-pro-collapse",
'vue-admin-beautiful-pro-collapse',
`{"collapse":${state.collapse}}`
);
)
},
toggleDevice(state, device) {
state.device = device;
state.device = device
},
changeHeader(state, header) {
state.header = header;
state.header = header
},
changeLayout(state, layout) {
state.layout = layout;
state.layout = layout
},
handleShowLanguage(state, showLanguage) {
state.showLanguage = showLanguage;
state.showLanguage = showLanguage
},
handleShowProgressBar(state, showProgressBar) {
state.showProgressBar = showProgressBar;
state.showProgressBar = showProgressBar
},
handleShowRefresh(state, showRefresh) {
state.showRefresh = showRefresh;
state.showRefresh = showRefresh
},
handleShowSearch(state, showSearch) {
state.showSearch = showSearch;
state.showSearch = showSearch
},
handleShowTheme(state, showTheme) {
state.showTheme = showTheme;
state.showTheme = showTheme
},
handleShowTagsBar(state, showTagsBar) {
state.showTagsBar = showTagsBar;
state.showTagsBar = showTagsBar
},
handleShowNotice(state, showNotice) {
state.showNotice = showNotice;
state.showNotice = showNotice
},
handleShowFullScreen(state, showFullScreen) {
state.showFullScreen = showFullScreen;
state.showFullScreen = showFullScreen
},
openSideBar(state) {
state.collapse = false;
state.collapse = false
},
foldSideBar(state) {
state.collapse = true;
state.collapse = true
},
changeLanguage(state, language) {
localStorage.setItem(
"vue-admin-beautiful-pro-language",
'vue-admin-beautiful-pro-language',
`{"language":"${language}"}`
);
state.language = language;
)
state.language = language
},
};
}
const actions = {
toggleCollapse({ commit }) {
commit("toggleCollapse");
commit('toggleCollapse')
},
toggleDevice({ commit }, device) {
commit("toggleDevice", device);
commit('toggleDevice', device)
},
changeHeader({ commit }, header) {
commit("changeHeader", header);
commit('changeHeader', header)
},
changeLayout({ commit }, layout) {
commit("changeLayout", layout);
commit('changeLayout', layout)
},
handleShowLanguage: ({ commit }, showLanguage) => {
commit("handleShowLanguage", showLanguage);
commit('handleShowLanguage', showLanguage)
},
handleShowProgressBar: ({ commit }, showProgressBar) => {
commit("handleShowProgressBar", showProgressBar);
commit('handleShowProgressBar', showProgressBar)
},
handleShowRefresh: ({ commit }, showRefresh) => {
commit("handleShowRefresh", showRefresh);
commit('handleShowRefresh', showRefresh)
},
handleShowSearch: ({ commit }, showSearch) => {
commit("handleShowSearch", showSearch);
commit('handleShowSearch', showSearch)
},
handleShowTheme: ({ commit }, showTheme) => {
commit("handleShowTheme", showTheme);
commit('handleShowTheme', showTheme)
},
handleShowTagsBar({ commit }, showTagsBar) {
commit("handleShowTagsBar", showTagsBar);
commit('handleShowTagsBar', showTagsBar)
},
handleShowNotice: ({ commit }, showNotice) => {
commit("handleShowNotice", showNotice);
commit('handleShowNotice', showNotice)
},
handleShowFullScreen: ({ commit }, showFullScreen) => {
commit("handleShowFullScreen", showFullScreen);
commit('handleShowFullScreen', showFullScreen)
},
openSideBar({ commit }) {
commit("openSideBar");
commit('openSideBar')
},
foldSideBar({ commit }) {
commit("foldSideBar");
commit('foldSideBar')
},
changeLanguage: ({ commit }, language) => {
commit("changeLanguage", language);
commit('changeLanguage', language)
},
};
export default { state, getters, mutations, actions };
}
export default { state, getters, mutations, actions }

View File

@ -5,10 +5,10 @@
const state = {
visitedRoutes: [],
};
}
const getters = {
visitedRoutes: (state) => state.visitedRoutes,
};
}
const mutations = {
/**
* @author chuzhixin 1204505056@qq.com
@ -18,12 +18,12 @@ const mutations = {
* @returns
*/
addVisitedRoute(state, route) {
let target = state.visitedRoutes.find((item) => item.path === route.path);
let target = state.visitedRoutes.find((item) => item.path === route.path)
if (target) {
if (route.fullPath !== target.fullPath) Object.assign(target, route);
return;
if (route.fullPath !== target.fullPath) Object.assign(target, route)
return
}
state.visitedRoutes.push(Object.assign({}, route));
state.visitedRoutes.push(Object.assign({}, route))
},
/**
* @author chuzhixin 1204505056@qq.com
@ -34,8 +34,8 @@ const mutations = {
*/
delVisitedRoute(state, route) {
state.visitedRoutes.forEach((item, index) => {
if (item.path === route.path) state.visitedRoutes.splice(index, 1);
});
if (item.path === route.path) state.visitedRoutes.splice(index, 1)
})
},
/**
* @author chuzhixin 1204505056@qq.com
@ -47,7 +47,7 @@ const mutations = {
delOthersVisitedRoutes(state, route) {
state.visitedRoutes = state.visitedRoutes.filter(
(item) => item.meta.affix || item.path === route.path
);
)
},
/**
* @author chuzhixin 1204505056@qq.com
@ -57,11 +57,11 @@ const mutations = {
* @returns
*/
delLeftVisitedRoutes(state, route) {
let index = state.visitedRoutes.length;
let index = state.visitedRoutes.length
state.visitedRoutes = state.visitedRoutes.filter((item) => {
if (item.name === route.name) index = state.visitedRoutes.indexOf(item);
return item.meta.affix || index <= state.visitedRoutes.indexOf(item);
});
if (item.name === route.name) index = state.visitedRoutes.indexOf(item)
return item.meta.affix || index <= state.visitedRoutes.indexOf(item)
})
},
/**
* @author chuzhixin 1204505056@qq.com
@ -71,11 +71,11 @@ const mutations = {
* @returns
*/
delRightVisitedRoutes(state, route) {
let index = state.visitedRoutes.length;
let index = state.visitedRoutes.length
state.visitedRoutes = state.visitedRoutes.filter((item) => {
if (item.name === route.name) index = state.visitedRoutes.indexOf(item);
return item.meta.affix || index >= state.visitedRoutes.indexOf(item);
});
if (item.name === route.name) index = state.visitedRoutes.indexOf(item)
return item.meta.affix || index >= state.visitedRoutes.indexOf(item)
})
},
/**
* @author chuzhixin 1204505056@qq.com
@ -85,9 +85,9 @@ const mutations = {
* @returns
*/
delAllVisitedRoutes(state) {
state.visitedRoutes = state.visitedRoutes.filter((item) => item.meta.affix);
state.visitedRoutes = state.visitedRoutes.filter((item) => item.meta.affix)
},
};
}
const actions = {
/**
* @author chuzhixin 1204505056@qq.com
@ -96,7 +96,7 @@ const actions = {
* @param {*} route
*/
addVisitedRoute({ commit }, route) {
commit("addVisitedRoute", route);
commit('addVisitedRoute', route)
},
/**
* @author chuzhixin 1204505056@qq.com
@ -105,7 +105,7 @@ const actions = {
* @param {*} route
*/
delVisitedRoute({ commit }, route) {
commit("delVisitedRoute", route);
commit('delVisitedRoute', route)
},
/**
* @author chuzhixin 1204505056@qq.com
@ -114,7 +114,7 @@ const actions = {
* @param {*} route
*/
delOthersVisitedRoutes({ commit }, route) {
commit("delOthersVisitedRoutes", route);
commit('delOthersVisitedRoutes', route)
},
/**
* @author chuzhixin 1204505056@qq.com
@ -123,7 +123,7 @@ const actions = {
* @param {*} route
*/
delLeftVisitedRoutes({ commit }, route) {
commit("delLeftVisitedRoutes", route);
commit('delLeftVisitedRoutes', route)
},
/**
* @author chuzhixin 1204505056@qq.com
@ -132,7 +132,7 @@ const actions = {
* @param {*} route
*/
delRightVisitedRoutes({ commit }, route) {
commit("delRightVisitedRoutes", route);
commit('delRightVisitedRoutes', route)
},
/**
* @author chuzhixin 1204505056@qq.com
@ -140,7 +140,7 @@ const actions = {
* @param {*} { commit }
*/
delAllVisitedRoutes({ commit }) {
commit("delAllVisitedRoutes");
commit('delAllVisitedRoutes')
},
};
export default { state, getters, mutations, actions };
}
export default { state, getters, mutations, actions }

View File

@ -2,25 +2,25 @@
* @author chuzhixin 1204505056@qq.com
* @description 登录获取用户信息退出登录清除accessToken逻辑不建议修改
*/
import { getUserInfo, login, logout } from "@/api/user";
import { getUserInfo, login, logout } from '@/api/user'
import {
getAccessToken,
removeAccessToken,
setAccessToken,
} from "@/utils/accessToken";
import { title, tokenName } from "@/config";
import { message, notification } from "ant-design-vue";
} from '@/utils/accessToken'
import { title, tokenName } from '@/config'
import { message, notification } from 'ant-design-vue'
const state = {
accessToken: getAccessToken(),
username: "",
avatar: "",
};
username: '',
avatar: '',
}
const getters = {
accessToken: (state) => state.accessToken,
username: (state) => state.username,
avatar: (state) => state.avatar,
};
}
const mutations = {
/**
* @author chuzhixin 1204505056@qq.com
@ -29,8 +29,8 @@ const mutations = {
* @param {*} accessToken
*/
setAccessToken(state, accessToken) {
state.accessToken = accessToken;
setAccessToken(accessToken);
state.accessToken = accessToken
setAccessToken(accessToken)
},
/**
* @author chuzhixin 1204505056@qq.com
@ -39,7 +39,7 @@ const mutations = {
* @param {*} username
*/
setUsername(state, username) {
state.username = username;
state.username = username
},
/**
* @author chuzhixin 1204505056@qq.com
@ -48,9 +48,9 @@ const mutations = {
* @param {*} avatar
*/
setAvatar(state, avatar) {
state.avatar = avatar;
state.avatar = avatar
},
};
}
const actions = {
/**
* @author chuzhixin 1204505056@qq.com
@ -58,12 +58,9 @@ const actions = {
* @param {*} { commit, dispatch }
*/
setVirtualRoles({ commit, dispatch }) {
dispatch("acl/setFull", true, { root: true });
commit(
"setAvatar",
"https://i.gtimg.cn/club/item/face/img/2/15922_100.gif"
);
commit("setUsername", "admin(未开启登录拦截)");
dispatch('acl/setFull', true, { root: true })
commit('setAvatar', 'https://i.gtimg.cn/club/item/face/img/2/15922_100.gif')
commit('setUsername', 'admin(未开启登录拦截)')
},
/**
* @author chuzhixin 1204505056@qq.com
@ -72,27 +69,27 @@ const actions = {
* @param {*} userInfo
*/
async login({ commit }, userInfo) {
const { data } = await login(userInfo);
const accessToken = data[tokenName];
const { data } = await login(userInfo)
const accessToken = data[tokenName]
if (accessToken) {
commit("setAccessToken", accessToken);
const hour = new Date().getHours();
commit('setAccessToken', accessToken)
const hour = new Date().getHours()
const thisTime =
hour < 8
? "早上好"
? '早上好'
: hour <= 11
? "上午好"
? '上午好'
: hour <= 13
? "中午好"
? '中午好'
: hour < 18
? "下午好"
: "晚上好";
? '下午好'
: '晚上好'
notification.open({
message: `欢迎登录${title}`,
description: `${thisTime}`,
});
})
} else {
message.error(`登录接口异常,未正确返回${tokenName}...`);
message.error(`登录接口异常,未正确返回${tokenName}...`)
}
},
/**
@ -102,20 +99,20 @@ const actions = {
* @returns
*/
async getUserInfo({ commit, dispatch, state }) {
const { data } = await getUserInfo(state.accessToken);
const { data } = await getUserInfo(state.accessToken)
if (!data) {
message.error(`验证失败,请重新登录...`);
return false;
message.error(`验证失败,请重新登录...`)
return false
}
let { username, avatar, roles, ability } = data;
let { username, avatar, roles, ability } = data
if (username && roles && Array.isArray(roles)) {
dispatch("acl/setRole", roles, { root: true });
dispatch('acl/setRole', roles, { root: true })
if (ability && ability.length > 0)
dispatch("acl/setAbility", ability, { root: true });
commit("setUsername", username);
commit("setAvatar", avatar);
dispatch('acl/setAbility', ability, { root: true })
commit('setUsername', username)
commit('setAvatar', avatar)
} else {
message.error("用户信息接口异常");
message.error('用户信息接口异常')
}
},
@ -125,8 +122,8 @@ const actions = {
* @param {*} { dispatch }
*/
async logout({ dispatch }) {
await logout(state.accessToken);
await dispatch("resetAll");
await logout(state.accessToken)
await dispatch('resetAll')
},
/**
* @author chuzhixin 1204505056@qq.com
@ -134,18 +131,18 @@ const actions = {
* @param {*} { commit, dispatch }
*/
async resetAll({ dispatch }) {
await dispatch("setAccessToken", "");
await dispatch("acl/setFull", false, { root: true });
await dispatch("acl/setRole", [], { root: true });
await dispatch("acl/setAbility", [], { root: true });
removeAccessToken();
await dispatch('setAccessToken', '')
await dispatch('acl/setFull', false, { root: true })
await dispatch('acl/setRole', [], { root: true })
await dispatch('acl/setAbility', [], { root: true })
removeAccessToken()
},
/**
* @author chuzhixin 1204505056@qq.com
* @description 设置token
*/
setAccessToken({ commit }, accessToken) {
commit("setAccessToken", accessToken);
commit('setAccessToken', accessToken)
},
};
export default { state, getters, mutations, actions };
}
export default { state, getters, mutations, actions }

View File

@ -1,5 +1,5 @@
import { storage, tokenTableName } from "@/config";
import cookie from "js-cookie";
import { storage, tokenTableName } from '@/config'
import cookie from 'js-cookie'
/**
* @author chuzhixin 1204505056@qq.com
@ -8,17 +8,17 @@ import cookie from "js-cookie";
*/
export function getAccessToken() {
if (storage) {
if ("localStorage" === storage) {
return localStorage.getItem(tokenTableName);
} else if ("sessionStorage" === storage) {
return sessionStorage.getItem(tokenTableName);
} else if ("cookie" === storage) {
return cookie.get(tokenTableName);
if ('localStorage' === storage) {
return localStorage.getItem(tokenTableName)
} else if ('sessionStorage' === storage) {
return sessionStorage.getItem(tokenTableName)
} else if ('cookie' === storage) {
return cookie.get(tokenTableName)
} else {
return localStorage.getItem(tokenTableName);
return localStorage.getItem(tokenTableName)
}
} else {
return localStorage.getItem(tokenTableName);
return localStorage.getItem(tokenTableName)
}
}
@ -30,17 +30,17 @@ export function getAccessToken() {
*/
export function setAccessToken(accessToken) {
if (storage) {
if ("localStorage" === storage) {
return localStorage.setItem(tokenTableName, accessToken);
} else if ("sessionStorage" === storage) {
return sessionStorage.setItem(tokenTableName, accessToken);
} else if ("cookie" === storage) {
return cookie.set(tokenTableName, accessToken);
if ('localStorage' === storage) {
return localStorage.setItem(tokenTableName, accessToken)
} else if ('sessionStorage' === storage) {
return sessionStorage.setItem(tokenTableName, accessToken)
} else if ('cookie' === storage) {
return cookie.set(tokenTableName, accessToken)
} else {
return localStorage.setItem(tokenTableName, accessToken);
return localStorage.setItem(tokenTableName, accessToken)
}
} else {
return localStorage.setItem(tokenTableName, accessToken);
return localStorage.setItem(tokenTableName, accessToken)
}
}
@ -51,16 +51,16 @@ export function setAccessToken(accessToken) {
*/
export function removeAccessToken() {
if (storage) {
if ("localStorage" === storage) {
return localStorage.removeItem(tokenTableName);
} else if ("sessionStorage" === storage) {
return sessionStorage.clear();
} else if ("cookie" === storage) {
return cookie.remove(tokenTableName);
if ('localStorage' === storage) {
return localStorage.removeItem(tokenTableName)
} else if ('sessionStorage' === storage) {
return sessionStorage.clear()
} else if ('cookie' === storage) {
return cookie.remove(tokenTableName)
} else {
return localStorage.removeItem(tokenTableName);
return localStorage.removeItem(tokenTableName)
}
} else {
return localStorage.removeItem(tokenTableName);
return localStorage.removeItem(tokenTableName)
}
}

View File

@ -1,51 +1,51 @@
import store from "@/store";
import store from '@/store'
export function hasRole(value) {
if (store.getters["acl/admin"]) return true;
if (store.getters['acl/admin']) return true
if (value instanceof Array && value.length > 0)
return can(store.getters["acl/role"], {
return can(store.getters['acl/role'], {
role: value,
mode: "oneOf",
});
let mode = "oneOf";
if (Object.prototype.hasOwnProperty.call(value, "mode")) mode = value["mode"];
let result = true;
if (Object.prototype.hasOwnProperty.call(value, "role"))
mode: 'oneOf',
})
let mode = 'oneOf'
if (Object.prototype.hasOwnProperty.call(value, 'mode')) mode = value['mode']
let result = true
if (Object.prototype.hasOwnProperty.call(value, 'role'))
result =
result && can(store.getters["acl/role"], { role: value["role"], mode });
if (result && Object.prototype.hasOwnProperty.call(value, "ability"))
result && can(store.getters['acl/role'], { role: value['role'], mode })
if (result && Object.prototype.hasOwnProperty.call(value, 'ability'))
result =
result &&
can(store.getters["acl/ability"], {
role: value["ability"],
can(store.getters['acl/ability'], {
role: value['ability'],
mode,
});
return result;
})
return result
}
export function can(roleOrAbility, value) {
let hasRole = false;
let hasRole = false
if (
value instanceof Object &&
Object.prototype.hasOwnProperty.call(value, "role") &&
Object.prototype.hasOwnProperty.call(value, "mode")
Object.prototype.hasOwnProperty.call(value, 'role') &&
Object.prototype.hasOwnProperty.call(value, 'mode')
) {
const { role, mode } = value;
if (mode === "allOf") {
const { role, mode } = value
if (mode === 'allOf') {
hasRole = role.every((item) => {
return roleOrAbility.includes(item);
});
return roleOrAbility.includes(item)
})
}
if (mode === "oneOf") {
if (mode === 'oneOf') {
hasRole = role.some((item) => {
return roleOrAbility.includes(item);
});
return roleOrAbility.includes(item)
})
}
if (mode === "except") {
if (mode === 'except') {
hasRole = !role.some((item) => {
return roleOrAbility.includes(item);
});
return roleOrAbility.includes(item)
})
}
}
return hasRole;
return hasRole
}

View File

@ -1,5 +1,5 @@
import { devDependencies } from "../../package.json";
if (!devDependencies["vab-config"]) document.body.innerHTML = "";
import { devDependencies } from '../../package.json'
if (!devDependencies['vab-config']) document.body.innerHTML = ''
/**
* @author chuzhixin 1204505056@qq.com
* @description 格式化时间
@ -9,20 +9,20 @@ if (!devDependencies["vab-config"]) document.body.innerHTML = "";
*/
export function parseTime(time, cFormat) {
if (arguments.length === 0) {
return null;
return null
}
const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
let date;
if (typeof time === "object") {
date = time;
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if (typeof time === "string" && /^[0-9]+$/.test(time)) {
time = parseInt(time);
if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
time = parseInt(time)
}
if (typeof time === "number" && time.toString().length === 10) {
time = time * 1000;
if (typeof time === 'number' && time.toString().length === 10) {
time = time * 1000
}
date = new Date(time);
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
@ -32,17 +32,17 @@ export function parseTime(time, cFormat) {
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay(),
};
}
return format.replace(/{([ymdhisa])+}/g, (result, key) => {
let value = formatObj[key];
if (key === "a") {
return ["日", "一", "二", "三", "四", "五", "六"][value];
let value = formatObj[key]
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value]
}
if (result.length > 0 && value < 10) {
value = "0" + value;
value = '0' + value
}
return value || 0;
});
return value || 0
})
}
/**
@ -53,40 +53,40 @@ export function parseTime(time, cFormat) {
* @returns {string}
*/
export function formatTime(time, option) {
if (("" + time).length === 10) {
time = parseInt(time) * 1000;
if (('' + time).length === 10) {
time = parseInt(time) * 1000
} else {
time = +time;
time = +time
}
const d = new Date(time);
const now = Date.now();
const d = new Date(time)
const now = Date.now()
const diff = (now - d) / 1000;
const diff = (now - d) / 1000
if (diff < 30) {
return "刚刚";
return '刚刚'
} else if (diff < 3600) {
// less 1 hour
return Math.ceil(diff / 60) + "分钟前";
return Math.ceil(diff / 60) + '分钟前'
} else if (diff < 3600 * 24) {
return Math.ceil(diff / 3600) + "小时前";
return Math.ceil(diff / 3600) + '小时前'
} else if (diff < 3600 * 24 * 2) {
return "1天前";
return '1天前'
}
if (option) {
return parseTime(time, option);
return parseTime(time, option)
} else {
return (
d.getMonth() +
1 +
"月" +
'月' +
d.getDate() +
"日" +
'日' +
d.getHours() +
"时" +
'时' +
d.getMinutes() +
"分"
);
'分'
)
}
}
@ -97,9 +97,9 @@ export function formatTime(time, option) {
* @returns {{}|any}
*/
export function paramObj(url) {
const search = url.split("?")[1];
const search = url.split('?')[1]
if (!search) {
return {};
return {}
}
return JSON.parse(
'{"' +
@ -107,9 +107,9 @@ export function paramObj(url) {
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"')
.replace(/\+/g, " ") +
.replace(/\+/g, ' ') +
'"}'
);
)
}
/**
@ -120,27 +120,27 @@ export function paramObj(url) {
*/
export function translateDataToTree(data) {
const parent = data.filter(
(value) => value.parentId === "undefined" || value.parentId == null
);
(value) => value.parentId === 'undefined' || value.parentId == null
)
const children = data.filter(
(value) => value.parentId !== "undefined" && value.parentId != null
);
(value) => value.parentId !== 'undefined' && value.parentId != null
)
const translator = (parent, children) => {
parent.forEach((parent) => {
children.forEach((current, index) => {
if (current.parentId === parent.id) {
const temp = JSON.parse(JSON.stringify(children));
temp.splice(index, 1);
translator([current], temp);
typeof parent.children !== "undefined"
const temp = JSON.parse(JSON.stringify(children))
temp.splice(index, 1)
translator([current], temp)
typeof parent.children !== 'undefined'
? parent.children.push(current)
: (parent.children = [current]);
: (parent.children = [current])
}
});
});
};
translator(parent, children);
return parent;
})
})
}
translator(parent, children)
return parent
}
/**
@ -150,24 +150,24 @@ export function translateDataToTree(data) {
* @returns {[]}
*/
export function translateTreeToData(data) {
const result = [];
const result = []
data.forEach((item) => {
const loop = (data) => {
result.push({
id: data.id,
name: data.name,
parentId: data.parentId,
});
const child = data.children;
})
const child = data.children
if (child) {
for (let i = 0; i < child.length; i++) {
loop(child[i]);
loop(child[i])
}
}
};
loop(item);
});
return result;
}
loop(item)
})
return result
}
/**
@ -177,19 +177,19 @@ export function translateTreeToData(data) {
* @returns {string}
*/
export function tenBitTimestamp(time) {
const date = new Date(time * 1000);
const y = date.getFullYear();
let m = date.getMonth() + 1;
m = m < 10 ? "" + m : m;
let d = date.getDate();
d = d < 10 ? "" + d : d;
let h = date.getHours();
h = h < 10 ? "0" + h : h;
let minute = date.getMinutes();
let second = date.getSeconds();
minute = minute < 10 ? "0" + minute : minute;
second = second < 10 ? "0" + second : second;
return y + "年" + m + "月" + d + "日 " + h + ":" + minute + ":" + second; //组合
const date = new Date(time * 1000)
const y = date.getFullYear()
let m = date.getMonth() + 1
m = m < 10 ? '' + m : m
let d = date.getDate()
d = d < 10 ? '' + d : d
let h = date.getHours()
h = h < 10 ? '0' + h : h
let minute = date.getMinutes()
let second = date.getSeconds()
minute = minute < 10 ? '0' + minute : minute
second = second < 10 ? '0' + second : second
return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second //组合
}
/**
@ -199,19 +199,19 @@ export function tenBitTimestamp(time) {
* @returns {string}
*/
export function thirteenBitTimestamp(time) {
const date = new Date(time / 1);
const y = date.getFullYear();
let m = date.getMonth() + 1;
m = m < 10 ? "" + m : m;
let d = date.getDate();
d = d < 10 ? "" + d : d;
let h = date.getHours();
h = h < 10 ? "0" + h : h;
let minute = date.getMinutes();
let second = date.getSeconds();
minute = minute < 10 ? "0" + minute : minute;
second = second < 10 ? "0" + second : second;
return y + "年" + m + "月" + d + "日 " + h + ":" + minute + ":" + second; //组合
const date = new Date(time / 1)
const y = date.getFullYear()
let m = date.getMonth() + 1
m = m < 10 ? '' + m : m
let d = date.getDate()
d = d < 10 ? '' + d : d
let h = date.getHours()
h = h < 10 ? '0' + h : h
let minute = date.getMinutes()
let second = date.getSeconds()
minute = minute < 10 ? '0' + minute : minute
second = second < 10 ? '0' + second : second
return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second //组合
}
/**
@ -221,12 +221,12 @@ export function thirteenBitTimestamp(time) {
* @returns {string}
*/
export function uuid(length = 32) {
const num = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
let str = "";
const num = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
let str = ''
for (let i = 0; i < length; i++) {
str += num.charAt(Math.floor(Math.random() * num.length));
str += num.charAt(Math.floor(Math.random() * num.length))
}
return str;
return str
}
/**
@ -237,7 +237,7 @@ export function uuid(length = 32) {
* @returns {number}
*/
export function random(m, n) {
return Math.floor(Math.random() * (m - n) + n);
return Math.floor(Math.random() * (m - n) + n)
}
/**
@ -248,10 +248,10 @@ export function random(m, n) {
export const on = (function () {
return function (element, event, handler, useCapture = false) {
if (element && event && handler) {
element.addEventListener(event, handler, useCapture);
element.addEventListener(event, handler, useCapture)
}
};
})();
}
})()
/**
* @author chuzhixin 1204505056@qq.com
@ -261,7 +261,7 @@ export const on = (function () {
export const off = (function () {
return function (element, event, handler, useCapture = false) {
if (element && event) {
element.removeEventListener(event, handler, useCapture);
element.removeEventListener(event, handler, useCapture)
}
};
})();
}
})()

View File

@ -1,4 +1,4 @@
import { title, titleReverse, titleSeparator } from "@/config";
import { title, titleReverse, titleSeparator } from '@/config'
/**
* @author chuzhixin 1204505056@qq.com
@ -7,9 +7,9 @@ import { title, titleReverse, titleSeparator } from "@/config";
* @returns {string}
*/
export default function getPageTitle(pageTitle) {
let newTitles = [];
if (pageTitle) newTitles.push(pageTitle);
if (title) newTitles.push(title);
if (titleReverse) newTitles = newTitles.reverse();
return newTitles.join(titleSeparator);
let newTitles = []
if (pageTitle) newTitles.push(pageTitle)
if (title) newTitles.push(title)
if (titleReverse) newTitles = newTitles.reverse()
return newTitles.join(titleSeparator)
}

View File

@ -1,4 +1,4 @@
import axios from "axios";
import axios from 'axios'
import {
baseURL,
contentType,
@ -6,14 +6,14 @@ import {
requestTimeout,
successCode,
tokenName,
} from "@/config";
import store from "@/store";
import qs from "qs";
import router from "@/router";
import { isArray } from "@/utils/validate";
import { message } from "ant-design-vue";
} from '@/config'
import store from '@/store'
import qs from 'qs'
import router from '@/router'
import { isArray } from '@/utils/validate'
import { message } from 'ant-design-vue'
let loadingInstance;
let loadingInstance
/**
* @author chuzhixin 1204505056@qq.com
@ -24,17 +24,17 @@ let loadingInstance;
const handleCode = (code, msg) => {
switch (code) {
case 401:
message.error(msg || "登录失效");
store.dispatch("user/resetAll").catch(() => {});
break;
message.error(msg || '登录失效')
store.dispatch('user/resetAll').catch(() => {})
break
case 403:
router.push({ path: "/401" }).catch(() => {});
break;
router.push({ path: '/401' }).catch(() => {})
break
default:
message.error(msg || `后端接口${code}异常`);
break;
message.error(msg || `后端接口${code}异常`)
break
}
};
}
/**
* @author chuzhixin 1204505056@qq.com
@ -44,9 +44,9 @@ const instance = axios.create({
baseURL,
timeout: requestTimeout,
headers: {
"Content-Type": contentType,
'Content-Type': contentType,
},
});
})
/**
* @author chuzhixin 1204505056@qq.com
@ -54,23 +54,23 @@ const instance = axios.create({
*/
instance.interceptors.request.use(
(config) => {
if (store.getters["user/accessToken"])
config.headers[tokenName] = store.getters["user/accessToken"];
if (store.getters['user/accessToken'])
config.headers[tokenName] = store.getters['user/accessToken']
if (
config.data &&
config.headers["Content-Type"] ===
"application/x-www-form-urlencoded;charset=UTF-8"
config.headers['Content-Type'] ===
'application/x-www-form-urlencoded;charset=UTF-8'
)
config.data = qs.stringify(config.data);
config.data = qs.stringify(config.data)
if (debounce.some((item) => config.url.includes(item))) {
//这里写加载动画
}
return config;
return config
},
(error) => {
return Promise.reject(error);
return Promise.reject(error)
}
);
)
/**
* @author chuzhixin 1204505056@qq.com
@ -78,48 +78,48 @@ instance.interceptors.request.use(
*/
instance.interceptors.response.use(
(response) => {
if (loadingInstance) loadingInstance.close();
if (loadingInstance) loadingInstance.close()
const { data, config } = response;
const { code, msg } = data;
const { data, config } = response
const { code, msg } = data
// 操作正常Code数组
const codeVerificationArray = isArray(successCode)
? [...successCode]
: [...[successCode]];
: [...[successCode]]
// 是否操作正常
if (codeVerificationArray.includes(code)) {
return data;
return data
} else {
handleCode(code, msg);
handleCode(code, msg)
return Promise.reject(
"vue-admin-beautiful请求异常拦截:" +
JSON.stringify({ url: config.url, code, msg }) || "Error"
);
'vue-admin-beautiful请求异常拦截:' +
JSON.stringify({ url: config.url, code, msg }) || 'Error'
)
}
},
(error) => {
if (loadingInstance) loadingInstance.close();
const { response, message } = error;
if (loadingInstance) loadingInstance.close()
const { response, message } = error
if (error.response && error.response.data) {
const { status, data } = response;
handleCode(status, data.msg || message);
return Promise.reject(error);
const { status, data } = response
handleCode(status, data.msg || message)
return Promise.reject(error)
} else {
let { message } = error;
if (message === "Network Error") {
message = "后端接口连接异常";
let { message } = error
if (message === 'Network Error') {
message = '后端接口连接异常'
}
if (message.includes("timeout")) {
message = "后端接口请求超时";
if (message.includes('timeout')) {
message = '后端接口请求超时'
}
if (message.includes("Request failed with status code")) {
const code = message.substr(message.length - 3);
message = "后端接口" + code + "异常";
if (message.includes('Request failed with status code')) {
const code = message.substr(message.length - 3)
message = '后端接口' + code + '异常'
}
message.error(message || `后端接口未知异常`);
return Promise.reject(error);
message.error(message || `后端接口未知异常`)
return Promise.reject(error)
}
}
);
)
export default instance;
export default instance

View File

@ -1,8 +1,8 @@
import router from "@/router";
import path from "path";
import { rolesControl } from "@/config";
import { isExternal } from "@/utils/validate";
import { hasRole } from "@/utils/hasRole";
import router from '@/router'
import path from 'path'
import { rolesControl } from '@/config'
import { isExternal } from '@/utils/validate'
import { hasRole } from '@/utils/hasRole'
/**
* @author chuzhixin 1204505056@qq.com
@ -13,33 +13,33 @@ import { hasRole } from "@/utils/hasRole";
export function convertRouter(constantRoutes) {
return constantRoutes.map((route) => {
if (route.component) {
if (route.component === "Layout") {
const path = "layouts";
route.component = (resolve) => require([`@/${path}`], resolve);
if (route.component === 'Layout') {
const path = 'layouts'
route.component = (resolve) => require([`@/${path}`], resolve)
} else {
let path = "views/" + route.component;
let path = 'views/' + route.component
if (
new RegExp("^/views/.*$").test(route.component) ||
new RegExp("^views/.*$").test(route.component)
new RegExp('^/views/.*$').test(route.component) ||
new RegExp('^views/.*$').test(route.component)
) {
path = route.component;
} else if (new RegExp("^/.*$").test(route.component)) {
path = "views" + route.component;
} else if (new RegExp("^@views/.*$").test(route.component)) {
path = route.component.slice(1);
path = route.component
} else if (new RegExp('^/.*$').test(route.component)) {
path = 'views' + route.component
} else if (new RegExp('^@views/.*$').test(route.component)) {
path = route.component.slice(1)
} else {
path = "views/" + route.component;
path = 'views/' + route.component
}
route.component = (resolve) => require([`@/${path}`], resolve);
route.component = (resolve) => require([`@/${path}`], resolve)
}
}
if (route.children && route.children.length)
route.children = convertRouter(route.children);
route.children = convertRouter(route.children)
if (route.children && route.children.length === 0) delete route.children;
if (route.children && route.children.length === 0) delete route.children
return route;
});
return route
})
}
/**
@ -49,21 +49,21 @@ export function convertRouter(constantRoutes) {
* @param baseUrl
* @returns {[]}
*/
export function filterRoutes(routes, baseUrl = "/") {
export function filterRoutes(routes, baseUrl = '/') {
return routes
.filter((route) => {
if (route.meta && route.meta.roles)
return !rolesControl || hasRole(route.meta.roles);
else return true;
return !rolesControl || hasRole(route.meta.roles)
else return true
})
.map((route) => {
if (route.path !== "*" && !isExternal(route.path))
route.path = path.resolve(baseUrl, route.path);
route.fullPath = route.path;
if (route.path !== '*' && !isExternal(route.path))
route.path = path.resolve(baseUrl, route.path)
route.fullPath = route.path
if (route.children)
route.children = filterRoutes(route.children, route.fullPath);
return route;
});
route.children = filterRoutes(route.children, route.fullPath)
return route
})
}
/**
@ -71,7 +71,7 @@ export function filterRoutes(routes, baseUrl = "/") {
* @returns {string}
*/
export function handleFirstMenu() {
const firstMenu = router.currentRoute.matched[0].path;
if (firstMenu === "") return "/";
return firstMenu;
const firstMenu = router.currentRoute.matched[0].path
if (firstMenu === '') return '/'
return firstMenu
}

View File

@ -2,51 +2,51 @@
* @author chuzhixin 1204505056@qq.com
* @description 导入所有 controller 模块浏览器环境中自动输出controller文件夹下Mock接口请勿修改
*/
import Mock from "mockjs";
import { paramObj } from "@/utils/index";
import Mock from 'mockjs'
import { paramObj } from '@/utils/index'
const mocks = [];
const files = require.context("../../mock/controller", false, /\.js$/);
const mocks = []
const files = require.context('../../mock/controller', false, /\.js$/)
files.keys().forEach((key) => {
mocks.push(...files(key));
});
mocks.push(...files(key))
})
export function mockXHR() {
Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send;
Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
Mock.XHR.prototype.send = function () {
if (this.custom.xhr) {
this.custom.xhr.withCredentials = this.withCredentials || false;
this.custom.xhr.withCredentials = this.withCredentials || false
if (this.responseType) {
this.custom.xhr.responseType = this.responseType;
this.custom.xhr.responseType = this.responseType
}
}
this.proxy_send(...arguments);
};
this.proxy_send(...arguments)
}
function XHRHttpRequst(respond) {
return function (options) {
let result;
let result
if (respond instanceof Function) {
const { body, type, url } = options;
const { body, type, url } = options
result = respond({
method: type,
body: JSON.parse(body),
query: paramObj(url),
});
})
} else {
result = respond;
result = respond
}
return Mock.mock(result);
};
return Mock.mock(result)
}
}
mocks.forEach((item) => {
Mock.mock(
new RegExp(item.url),
item.type || "get",
item.type || 'get',
XHRHttpRequst(item.response)
);
});
)
})
}

View File

@ -5,7 +5,7 @@
* @returns {boolean}
*/
export function isExternal(path) {
return /^(https?:|mailto:|tel:)/.test(path);
return /^(https?:|mailto:|tel:)/.test(path)
}
/**
@ -15,7 +15,7 @@ export function isExternal(path) {
* @returns {boolean}
*/
export function isPassword(value) {
return value.length >= 6;
return value.length >= 6
}
/**
@ -25,8 +25,8 @@ export function isPassword(value) {
* @returns {boolean}
*/
export function isNumber(value) {
const reg = /^[0-9]*$/;
return reg.test(value);
const reg = /^[0-9]*$/
return reg.test(value)
}
/**
@ -36,8 +36,8 @@ export function isNumber(value) {
* @returns {boolean}
*/
export function isName(value) {
const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/;
return reg.test(value);
const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/
return reg.test(value)
}
/**
@ -47,8 +47,8 @@ export function isName(value) {
* @returns {boolean}
*/
export function isIP(ip) {
const reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
return reg.test(ip);
const reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
return reg.test(ip)
}
/**
@ -58,8 +58,8 @@ export function isIP(ip) {
* @returns {boolean}
*/
export function isUrl(url) {
const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
return reg.test(url);
const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
return reg.test(url)
}
/**
@ -69,8 +69,8 @@ export function isUrl(url) {
* @returns {boolean}
*/
export function isLowerCase(value) {
const reg = /^[a-z]+$/;
return reg.test(value);
const reg = /^[a-z]+$/
return reg.test(value)
}
/**
@ -80,8 +80,8 @@ export function isLowerCase(value) {
* @returns {boolean}
*/
export function isUpperCase(value) {
const reg = /^[A-Z]+$/;
return reg.test(value);
const reg = /^[A-Z]+$/
return reg.test(value)
}
/**
@ -91,8 +91,8 @@ export function isUpperCase(value) {
* @returns {boolean}
*/
export function isAlphabets(value) {
const reg = /^[A-Za-z]+$/;
return reg.test(value);
const reg = /^[A-Za-z]+$/
return reg.test(value)
}
/**
@ -102,7 +102,7 @@ export function isAlphabets(value) {
* @returns {boolean}
*/
export function isString(value) {
return typeof value === "string" || value instanceof String;
return typeof value === 'string' || value instanceof String
}
/**
@ -112,10 +112,10 @@ export function isString(value) {
* @returns {arg is any[]|boolean}
*/
export function isArray(arg) {
if (typeof Array.isArray === "undefined") {
return Object.prototype.toString.call(arg) === "[object Array]";
if (typeof Array.isArray === 'undefined') {
return Object.prototype.toString.call(arg) === '[object Array]'
}
return Array.isArray(arg);
return Array.isArray(arg)
}
/**
@ -125,8 +125,8 @@ export function isArray(arg) {
* @returns {boolean}
*/
export function isPort(value) {
const reg = /^([0-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/;
return reg.test(value);
const reg = /^([0-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/
return reg.test(value)
}
/**
@ -136,8 +136,8 @@ export function isPort(value) {
* @returns {boolean}
*/
export function isPhone(value) {
const reg = /^1\d{10}$/;
return reg.test(value);
const reg = /^1\d{10}$/
return reg.test(value)
}
/**
@ -147,8 +147,8 @@ export function isPhone(value) {
* @returns {boolean}
*/
export function isIdCard(value) {
const reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
return reg.test(value);
const reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
return reg.test(value)
}
/**
@ -158,8 +158,8 @@ export function isIdCard(value) {
* @returns {boolean}
*/
export function isEmail(value) {
const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
return reg.test(value);
const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
return reg.test(value)
}
/**
@ -169,8 +169,8 @@ export function isEmail(value) {
* @returns {boolean}
*/
export function isChina(value) {
const reg = /^[\u4E00-\u9FA5]{2,4}$/;
return reg.test(value);
const reg = /^[\u4E00-\u9FA5]{2,4}$/
return reg.test(value)
}
/**
@ -183,10 +183,10 @@ export function isBlank(value) {
return (
value == null ||
false ||
value === "" ||
value.trim() === "" ||
value.toLocaleLowerCase().trim() === "null"
);
value === '' ||
value.trim() === '' ||
value.toLocaleLowerCase().trim() === 'null'
)
}
/**
@ -196,8 +196,8 @@ export function isBlank(value) {
* @returns {boolean}
*/
export function isTel(value) {
const reg = /^(400|800)([0-9\\-]{7,10})|(([0-9]{4}|[0-9]{3})([- ])?)?([0-9]{7,8})(([- 转])*([0-9]{1,4}))?$/;
return reg.test(value);
const reg = /^(400|800)([0-9\\-]{7,10})|(([0-9]{4}|[0-9]{3})([- ])?)?([0-9]{7,8})(([- 转])*([0-9]{1,4}))?$/
return reg.test(value)
}
/**
@ -207,8 +207,8 @@ export function isTel(value) {
* @returns {boolean}
*/
export function isNum(value) {
const reg = /^\d+(\.\d{1,2})?$/;
return reg.test(value);
const reg = /^\d+(\.\d{1,2})?$/
return reg.test(value)
}
/**
@ -218,8 +218,8 @@ export function isNum(value) {
* @returns {boolean}
*/
export function isLongitude(value) {
const reg = /^[-|+]?(0?\d{1,2}\.\d{1,5}|1[0-7]?\d{1}\.\d{1,5}|180\.0{1,5})$/;
return reg.test(value);
const reg = /^[-|+]?(0?\d{1,2}\.\d{1,5}|1[0-7]?\d{1}\.\d{1,5}|180\.0{1,5})$/
return reg.test(value)
}
/**
@ -229,8 +229,8 @@ export function isLongitude(value) {
* @returns {boolean}
*/
export function isLatitude(value) {
const reg = /^[-|+]?([0-8]?\d{1}\.\d{1,5}|90\.0{1,5})$/;
return reg.test(value);
const reg = /^[-|+]?([0-8]?\d{1}\.\d{1,5}|90\.0{1,5})$/
return reg.test(value)
}
/**
@ -240,10 +240,10 @@ export function isLatitude(value) {
* @returns {boolean}
*/
export function isRTSP(value) {
const reg = /^rtsp:\/\/([a-z]{0,10}:.{0,10}@)?(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
const reg1 = /^rtsp:\/\/([a-z]{0,10}:.{0,10}@)?(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]):[0-9]{1,5}/;
const reg2 = /^rtsp:\/\/([a-z]{0,10}:.{0,10}@)?(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\//;
return reg.test(value) || reg1.test(value) || reg2.test(value);
const reg = /^rtsp:\/\/([a-z]{0,10}:.{0,10}@)?(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
const reg1 = /^rtsp:\/\/([a-z]{0,10}:.{0,10}@)?(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]):[0-9]{1,5}/
const reg2 = /^rtsp:\/\/([a-z]{0,10}:.{0,10}@)?(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\//
return reg.test(value) || reg1.test(value) || reg2.test(value)
}
/**
@ -253,16 +253,16 @@ export function isRTSP(value) {
* @returns {boolean}
*/
export function isJson(value) {
if (typeof value == "string") {
if (typeof value == 'string') {
try {
var obj = JSON.parse(value);
if (typeof obj == "object" && obj) {
return true;
var obj = JSON.parse(value)
if (typeof obj == 'object' && obj) {
return true
} else {
return false;
return false
}
} catch (e) {
return false;
return false
}
}
}

View File

@ -1,5 +1,5 @@
// 加载插件
const requirePlugin = require.context("./plugins", true, /\.js$/);
const requirePlugin = require.context('./plugins', true, /\.js$/)
requirePlugin.keys().forEach((fileName) => {
requirePlugin(fileName);
});
requirePlugin(fileName)
})

View File

@ -2,73 +2,73 @@
* @author chuzhixin 1204505056@qq.com
* @description 路由守卫目前两种模式all模式与intelligence模式
*/
import router from "@/router";
import store from "@/store";
import getPageTitle from "@/utils/pageTitle";
import router from '@/router'
import store from '@/store'
import getPageTitle from '@/utils/pageTitle'
import {
authentication,
loginInterception,
recordRoute,
routesWhiteList,
} from "@/config";
} from '@/config'
router.beforeEach(async (to, from, next) => {
let hasToken = store.getters["user/accessToken"];
let hasToken = store.getters['user/accessToken']
if (!loginInterception) hasToken = true;
if (!loginInterception) hasToken = true
if (hasToken) {
if (to.path === "/login") {
next({ path: "/" });
if (to.path === '/login') {
next({ path: '/' })
} else {
const hasRoles =
store.getters["acl/admin"] ||
store.getters["acl/role"].length > 0 ||
store.getters["acl/ability"].length > 0;
store.getters['acl/admin'] ||
store.getters['acl/role'].length > 0 ||
store.getters['acl/ability'].length > 0
if (hasRoles) {
next();
next()
} else {
try {
if (loginInterception) {
await store.dispatch("user/getUserInfo");
await store.dispatch('user/getUserInfo')
} else {
//loginInterception为false关闭登录拦截时创建虚拟角色
await store.dispatch("user/setVirtualRoles");
await store.dispatch('user/setVirtualRoles')
}
let accessRoutes = [];
if (authentication === "intelligence") {
accessRoutes = await store.dispatch("routes/setRoutes");
} else if (authentication === "all") {
accessRoutes = await store.dispatch("routes/setAllRoutes");
let accessRoutes = []
if (authentication === 'intelligence') {
accessRoutes = await store.dispatch('routes/setRoutes')
} else if (authentication === 'all') {
accessRoutes = await store.dispatch('routes/setAllRoutes')
}
accessRoutes.forEach((item) => {
router.addRoute(item);
});
router.addRoute(item)
})
next({ ...to, replace: true });
next({ ...to, replace: true })
} catch {
await store.dispatch("user/resetAll");
await store.dispatch('user/resetAll')
if (recordRoute)
next({
path: "/login",
path: '/login',
query: { redirect: to.path },
replace: true,
});
else next({ path: "/login", replace: true });
})
else next({ path: '/login', replace: true })
}
}
}
} else {
if (routesWhiteList.indexOf(to.path) !== -1) {
next();
next()
} else {
if (recordRoute)
next({ path: "/login", query: { redirect: to.path }, replace: true });
else next({ path: "/login", replace: true });
next({ path: '/login', query: { redirect: to.path }, replace: true })
else next({ path: '/login', replace: true })
}
}
});
})
router.afterEach((to) => {
document.title = getPageTitle(to.meta.title);
});
document.title = getPageTitle(to.meta.title)
})

View File

@ -28,44 +28,44 @@
</template>
<script>
import { mapActions } from "vuex";
import { mapActions } from 'vuex'
export default {
name: "Page403",
name: 'Page403',
data() {
return {
jumpTime: 5,
oops: "抱歉!",
headline: "您没有操作角色...",
info: "当前帐号没有操作角色,请联系管理员。",
btn: "返回首页",
oops: '抱歉!',
headline: '您没有操作角色...',
info: '当前帐号没有操作角色,请联系管理员。',
btn: '返回首页',
timer: 0,
};
}
},
mounted() {
this.timeChange();
this.timeChange()
},
beforeUnmount() {
clearInterval(this.timer);
clearInterval(this.timer)
},
methods: {
...mapActions({
delVisitedRoute: "tagsBar/delVisitedRoute",
delOthersVisitedRoutes: "tagsBar/delOthersVisitedRoutes",
delVisitedRoute: 'tagsBar/delVisitedRoute',
delOthersVisitedRoutes: 'tagsBar/delOthersVisitedRoutes',
}),
timeChange() {
this.timer = setInterval(() => {
if (this.jumpTime) {
this.jumpTime--;
this.jumpTime--
} else {
this.$router.push({ path: "/" });
this.delOthersVisitedRoutes({ path: "/" });
clearInterval(this.timer);
this.$router.push({ path: '/' })
this.delOthersVisitedRoutes({ path: '/' })
clearInterval(this.timer)
}
}, 1000);
}, 1000)
},
},
};
}
</script>
<style lang="less" scoped>

View File

@ -28,43 +28,43 @@
</template>
<script>
import { mapActions } from "vuex";
import { mapActions } from 'vuex'
export default {
name: "Page404",
name: 'Page404',
data() {
return {
jumpTime: 5,
oops: "抱歉!",
headline: "当前页面不存在...",
info: "请检查您输入的网址是否正确,或点击下面的按钮返回首页。",
btn: "返回首页",
oops: '抱歉!',
headline: '当前页面不存在...',
info: '请检查您输入的网址是否正确,或点击下面的按钮返回首页。',
btn: '返回首页',
timer: 0,
};
}
},
mounted() {
this.timeChange();
this.timeChange()
},
beforeUnmount() {
clearInterval(this.timer);
clearInterval(this.timer)
},
methods: {
...mapActions({
delOthersVisitedRoutes: "tagsBar/delOthersVisitedRoutes",
delOthersVisitedRoutes: 'tagsBar/delOthersVisitedRoutes',
}),
timeChange() {
this.timer = setInterval(() => {
if (this.jumpTime) {
this.jumpTime--;
this.jumpTime--
} else {
this.$router.push({ path: "/" });
this.delOthersVisitedRoutes({ path: "/" });
clearInterval(this.timer);
this.$router.push({ path: '/' })
this.delOthersVisitedRoutes({ path: '/' })
clearInterval(this.timer)
}
}, 1000);
}, 1000)
},
},
};
}
</script>
<style lang="less" scoped>

View File

@ -36,27 +36,27 @@
</tr>
<tr>
<td>vue</td>
<td>{{ dependencies["vue"] }}</td>
<td>{{ dependencies['vue'] }}</td>
<td>@vue/cli</td>
<td>{{ devDependencies["@vue/cli-service"] }}</td>
<td>{{ devDependencies['@vue/cli-service'] }}</td>
</tr>
<tr>
<td>vuex</td>
<td>{{ dependencies["vuex"] }}</td>
<td>{{ dependencies['vuex'] }}</td>
<td>vue-router</td>
<td>{{ dependencies["vue-router"] }}</td>
<td>{{ dependencies['vue-router'] }}</td>
</tr>
<tr>
<td>eslint-plugin-vue</td>
<td>{{ devDependencies["eslint-plugin-vue"] }}</td>
<td>{{ devDependencies['eslint-plugin-vue'] }}</td>
<td>axios</td>
<td>{{ dependencies["axios"] }}</td>
<td>{{ dependencies['axios'] }}</td>
</tr>
<tr>
<td>babel-eslint</td>
<td>{{ devDependencies["babel-eslint"] }}</td>
<td>{{ devDependencies['babel-eslint'] }}</td>
<td>ant-design-vue</td>
<td>{{ dependencies["ant-design-vue"] }}</td>
<td>{{ dependencies['ant-design-vue'] }}</td>
</tr>
<tr>
<td>v2.x版演示地址MIT协议商用免费</td>
@ -113,7 +113,7 @@
</a-card>
</template>
<script>
import { dependencies, devDependencies } from "*/package.json";
import { dependencies, devDependencies } from '*/package.json'
export default {
data() {
@ -121,9 +121,9 @@
updateTime: process.env.VUE_APP_UPDATE_TIME,
dependencies: dependencies,
devDependencies: devDependencies,
};
}
},
};
}
</script>
<style lang="less" scoped>
.version-information {

View File

@ -5,9 +5,9 @@
</template>
<script>
import VersionInformation from "./components/VersionInformation";
import VersionInformation from './components/VersionInformation'
export default {
name: "Index",
name: 'Index',
components: { VersionInformation },
};
}
</script>

View File

@ -35,9 +35,9 @@
登录
</a-button>
<div class="login-container-tips">
基于vue{{ dependencies["vue"] }}
基于vue{{ dependencies['vue'] }}
+ ant-design-vue
{{ dependencies["ant-design-vue"] }}开发
{{ dependencies['ant-design-vue'] }}开发
</div>
</a-form-item>
</a-form>
@ -48,12 +48,12 @@
</div>
</template>
<script>
import { dependencies, devDependencies } from "*/package.json";
import { mapActions, mapGetters } from "vuex";
import { UserOutlined, LockOutlined } from "@ant-design/icons-vue";
import { dependencies, devDependencies } from '*/package.json'
import { mapActions, mapGetters } from 'vuex'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
export default {
name: "Login",
name: 'Login',
components: {
UserOutlined,
LockOutlined,
@ -61,55 +61,55 @@
data() {
return {
form: {
username: "",
password: "",
username: '',
password: '',
},
redirect: undefined,
dependencies: dependencies,
devDependencies: devDependencies,
};
}
},
computed: {
...mapGetters({
logo: "settings/logo",
title: "settings/title",
logo: 'settings/logo',
title: 'settings/title',
}),
},
watch: {
$route: {
handler(route) {
this.redirect = (route.query && route.query.redirect) || "/";
this.redirect = (route.query && route.query.redirect) || '/'
},
immediate: true,
},
},
mounted() {
this.form.username = "admin";
this.form.password = "123456";
this.form.username = 'admin'
this.form.password = '123456'
setTimeout(() => {
this.handleSubmit();
}, 500000);
this.handleSubmit()
}, 500000)
},
methods: {
...mapActions({
login: "user/login",
login: 'user/login',
}),
handleRoute() {
return this.redirect === "/404" || this.redirect === "/403"
? "/"
: this.redirect;
return this.redirect === '/404' || this.redirect === '/403'
? '/'
: this.redirect
},
async handleSubmit() {
await this.login(this.form);
await this.$router.push(this.handleRoute());
await this.login(this.form)
await this.$router.push(this.handleRoute())
},
},
};
}
</script>
<style lang="less">
.login-container {
height: 100vh;
background: url("~@/assets/login_images/login_background.png");
background: url('~@/assets/login_images/login_background.png');
background-size: cover;
&-form {
width: calc(100% - 40px);
@ -118,7 +118,7 @@
margin-top: calc((100vh - 380px) / 2);
margin-right: 20px;
margin-left: 20px;
background: url("~@/assets/login_images/login_form.png");
background: url('~@/assets/login_images/login_form.png');
background-size: 100% 100%;
border-radius: 10px;
box-shadow: 0 2px 8px 0 rgba(7, 17, 27, 0.06);

View File

@ -6,6 +6,6 @@
<script>
export default {
name: "Test",
};
name: 'Test',
}
</script>

View File

@ -9,25 +9,25 @@
></a-table>
</template>
<script>
import { getList } from "@/api/table";
import { getList } from '@/api/table'
const columns = [
{
title: "title",
dataIndex: "title",
title: 'title',
dataIndex: 'title',
},
{
title: "description",
dataIndex: "description",
title: 'description',
dataIndex: 'description',
},
{
title: "author",
dataIndex: "author",
title: 'author',
dataIndex: 'author',
},
{
title: "datetime",
dataIndex: "datetime",
title: 'datetime',
dataIndex: 'datetime',
},
];
]
export default {
data() {
@ -41,31 +41,31 @@
query: {},
loading: false,
columns,
};
}
},
mounted() {
this.fetch();
this.fetch()
},
methods: {
handleTableChange(pagination) {
const pager = { ...this.pagination };
pager.current = pagination.current;
this.pagination = pager;
this.fetch();
const pager = { ...this.pagination }
pager.current = pagination.current
this.pagination = pager
this.fetch()
},
fetch() {
this.loading = true;
this.loading = true
getList({
pageSize: this.pagination.pageSize,
current: this.pagination.current,
}).then(({ data, total }) => {
const pagination = { ...this.pagination };
pagination.total = total;
this.loading = false;
this.data = data;
this.pagination = pagination;
});
const pagination = { ...this.pagination }
pagination.total = total
this.loading = false
this.data = data
this.pagination = pagination
})
},
},
};
}
</script>

View File

@ -2,7 +2,7 @@
* @author chuzhixin 1204505056@qq.com
* @description vue.config.js全局配置
*/
const path = require("path");
const path = require('path')
const {
/* baseURL, */
publicPath,
@ -16,39 +16,35 @@ const {
providePlugin,
build7z,
donation,
} = require("./src/config");
const {
webpackBarName,
webpackBanner,
donationConsole,
} = require("vab-config");
} = require('./src/config')
const { webpackBarName, webpackBanner, donationConsole } = require('vab-config')
if (donation) donationConsole();
const { version, author } = require("./package.json");
const Webpack = require("webpack");
const WebpackBar = require("webpackbar");
const FileManagerPlugin = require("filemanager-webpack-plugin");
const dayjs = require("dayjs");
const date = dayjs().format("YYYY_M_D");
const time = dayjs().format("YYYY-M-D HH:mm:ss");
const CompressionWebpackPlugin = require("compression-webpack-plugin");
const productionGzipExtensions = ["html", "js", "css", "svg"];
process.env.VUE_APP_TITLE = title || "vue-admin-beautiful";
process.env.VUE_APP_AUTHOR = author || "chuzhixin";
process.env.VUE_APP_UPDATE_TIME = time;
process.env.VUE_APP_VERSION = version;
if (donation) donationConsole()
const { version, author } = require('./package.json')
const Webpack = require('webpack')
const WebpackBar = require('webpackbar')
const FileManagerPlugin = require('filemanager-webpack-plugin')
const dayjs = require('dayjs')
const date = dayjs().format('YYYY_M_D')
const time = dayjs().format('YYYY-M-D HH:mm:ss')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = ['html', 'js', 'css', 'svg']
process.env.VUE_APP_TITLE = title || 'vue-admin-beautiful'
process.env.VUE_APP_AUTHOR = author || 'chuzhixin'
process.env.VUE_APP_UPDATE_TIME = time
process.env.VUE_APP_VERSION = version
const resolve = (dir) => {
return path.join(__dirname, dir);
};
return path.join(__dirname, dir)
}
const mockServer = () => {
if (process.env.NODE_ENV === "development") {
return require("./mock/mockServer.js");
if (process.env.NODE_ENV === 'development') {
return require('./mock/mockServer.js')
} else {
return "";
return ''
}
};
}
module.exports = {
publicPath,
@ -82,8 +78,8 @@ module.exports = {
return {
resolve: {
alias: {
"@": resolve("src"),
"*": resolve(""),
'@': resolve('src'),
'*': resolve(''),
},
},
plugins: [
@ -92,64 +88,64 @@ module.exports = {
name: webpackBarName,
}),
],
};
}
},
chainWebpack(config) {
config.resolve.symlinks(true);
config.module.rule("svg").exclude.add(resolve("src/icon/remixIcon")).end();
config.resolve.symlinks(true)
config.module.rule('svg').exclude.add(resolve('src/icon/remixIcon')).end()
config.module
.rule("remixIcon")
.rule('remixIcon')
.test(/\.svg$/)
.include.add(resolve("src/icon/remixIcon"))
.include.add(resolve('src/icon/remixIcon'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({ symbolId: 'remix-icon-[name]' })
.end()
.use("svg-sprite-loader")
.loader("svg-sprite-loader")
.options({ symbolId: "remix-icon-[name]" })
.end();
config.when(process.env.NODE_ENV === "development", (config) => {
config.devtool("source-map");
});
config.when(process.env.NODE_ENV === 'development', (config) => {
config.devtool('source-map')
})
config.when(process.env.NODE_ENV !== "development", (config) => {
config.performance.set("hints", false);
config.devtool("none");
config.when(process.env.NODE_ENV !== 'development', (config) => {
config.performance.set('hints', false)
config.devtool('none')
config.optimization.splitChunks({
chunks: "all",
chunks: 'all',
cacheGroups: {
libs: {
name: "vue-admin-beautiful-libs",
name: 'vue-admin-beautiful-libs',
test: /[\\/]node_modules[\\/]/,
priority: 10,
chunks: "initial",
chunks: 'initial',
},
},
});
})
config
.plugin("banner")
.plugin('banner')
.use(Webpack.BannerPlugin, [`${webpackBanner}${time}`])
.end();
.end()
config
.plugin("compression")
.plugin('compression')
.use(CompressionWebpackPlugin, [
{
filename: "[path].gz[query]",
algorithm: "gzip",
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
"\\.(" + productionGzipExtensions.join("|") + ")$"
'\\.(' + productionGzipExtensions.join('|') + ')$'
),
threshold: 8192,
minRatio: 0.8,
},
])
.end();
});
.end()
})
if (build7z) {
config.when(process.env.NODE_ENV === "production", (config) => {
config.when(process.env.NODE_ENV === 'production', (config) => {
config
.plugin("fileManager")
.plugin('fileManager')
.use(FileManagerPlugin, [
{
onEnd: {
@ -163,8 +159,8 @@ module.exports = {
},
},
])
.end();
});
.end()
})
}
},
runtimeCompiler: true,
@ -177,13 +173,13 @@ module.exports = {
lessOptions: {
javascriptEnabled: true,
modifyVars: {
"vab-color-blue": "#1890ff",
"vab-margin": "20px",
"vab-padding": "20px",
"vab-header-height": "65px",
'vab-color-blue': '#1890ff',
'vab-margin': '20px',
'vab-padding': '20px',
'vab-header-height': '65px',
},
},
},
},
},
};
}