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

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: { env: {
node: true, node: true,
}, },
extends: ["plugin:vue/vue3-essential", "eslint:recommended", "@vue/prettier"], extends: ['plugin:vue/vue3-essential', 'eslint:recommended', '@vue/prettier'],
parserOptions: { parserOptions: {
parser: "babel-eslint", parser: 'babel-eslint',
}, },
rules: { rules: {
"no-console": 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", 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
}, },
}; }

View File

@ -1,3 +1,3 @@
module.exports = { 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 = { module.exports = {
presets: ["@vue/cli-plugin-babel/preset"], presets: ['@vue/cli-plugin-babel/preset'],
}; }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,8 +2,8 @@
* @description 3个子配置通用配置|主题配置|网络配置建议在当前目录下修改config.js修改配置会覆盖默认配置也可以直接修改默认配置 * @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> </a-layout>
</template> </template>
<script> <script>
import VabLogo from "./vab-logo"; import VabLogo from './vab-logo'
import VabAvatar from "./vab-avatar"; import VabAvatar from './vab-avatar'
import VabMenu from "./vab-menu"; import VabMenu from './vab-menu'
import VabTabs from "./vab-tabs"; import VabTabs from './vab-tabs'
import VabContent from "./vab-content"; import VabContent from './vab-content'
import { mapActions, mapGetters } from "vuex"; import { mapActions, mapGetters } from 'vuex'
import { MenuUnfoldOutlined, MenuFoldOutlined } from "@ant-design/icons-vue"; import { MenuUnfoldOutlined, MenuFoldOutlined } from '@ant-design/icons-vue'
export default { export default {
components: { components: {
@ -68,58 +68,58 @@
}, },
data() { data() {
return { return {
selectedKeys: ["/index"], selectedKeys: ['/index'],
}; }
}, },
computed: { computed: {
...mapGetters({ ...mapGetters({
collapse: "settings/collapse", collapse: 'settings/collapse',
routes: "routes/routes", routes: 'routes/routes',
device: "settings/device", device: 'settings/device',
}), }),
classObj() { classObj() {
return { return {
"vab-mobile": this.device === "mobile", 'vab-mobile': this.device === 'mobile',
"vab-collapse": this.collapse, 'vab-collapse': this.collapse,
}; }
}, },
}, },
watch: { watch: {
$route: { $route: {
handler({ fullPath }) { handler({ fullPath }) {
// //
if (fullPath === "/index") fullPath = "/"; if (fullPath === '/index') fullPath = '/'
if (fullPath === "/test/test") fullPath = "/test"; if (fullPath === '/test/test') fullPath = '/test'
this.selectedKeys = [fullPath]; this.selectedKeys = [fullPath]
}, },
immediate: true, immediate: true,
}, },
}, },
beforeMount() { beforeMount() {
window.addEventListener("resize", this.handleLayouts); window.addEventListener('resize', this.handleLayouts)
}, },
beforeUnmount() { beforeUnmount() {
window.removeEventListener("resize", this.handleLayouts); window.removeEventListener('resize', this.handleLayouts)
}, },
mounted() { mounted() {
this.handleLayouts(); this.handleLayouts()
}, },
methods: { methods: {
...mapActions({ ...mapActions({
toggleDevice: "settings/toggleDevice", toggleDevice: 'settings/toggleDevice',
handleFoldSideBar: "settings/foldSideBar", handleFoldSideBar: 'settings/foldSideBar',
toggleCollapse: "settings/toggleCollapse", toggleCollapse: 'settings/toggleCollapse',
}), }),
handleLayouts() { handleLayouts() {
const width = document.body.getBoundingClientRect().width; const width = document.body.getBoundingClientRect().width
if (this.width !== width) { if (this.width !== width) {
const isMobile = width - 1 < 992; const isMobile = width - 1 < 992
this.toggleDevice(isMobile ? "mobile" : "desktop"); this.toggleDevice(isMobile ? 'mobile' : 'desktop')
this.width = width; this.width = width
} }
}, },
}, },
}; }
</script> </script>
<style lang="less"> <style lang="less">
.ant-layout-content { .ant-layout-content {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,17 +1,17 @@
import { createApp } from "vue"; import { createApp } from 'vue'
import Antd from "ant-design-vue"; import Antd from 'ant-design-vue'
import App from "./App"; import App from './App'
import router from "./router"; import router from './router'
import store from "./store"; import store from './store'
import "ant-design-vue/dist/antd.css"; import 'ant-design-vue/dist/antd.css'
import "@/vab"; import '@/vab'
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
* @description 正式环境默认使用mock正式项目记得注释后再打包 * @description 正式环境默认使用mock正式项目记得注释后再打包
*/ */
if (process.env.NODE_ENV === "production") { if (process.env.NODE_ENV === 'production') {
const { mockXHR } = require("@/utils/static"); const { mockXHR } = require('@/utils/static')
mockXHR(); 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 { createRouter, createWebHashHistory } from 'vue-router'
import Layout from "@/layout"; import Layout from '@/layout'
export const constantRoutes = [ export const constantRoutes = [
{ {
path: "/login", path: '/login',
component: () => import("@/views/login"), component: () => import('@/views/login'),
hidden: true, hidden: true,
}, },
{ {
path: "/403", path: '/403',
name: "403", name: '403',
component: () => import("@/views/403"), component: () => import('@/views/403'),
hidden: true, hidden: true,
}, },
{ {
path: "/404", path: '/404',
name: "404", name: '404',
component: () => import("@/views/404"), component: () => import('@/views/404'),
hidden: true, hidden: true,
}, },
]; ]
export const asyncRoutes = [ export const asyncRoutes = [
{ {
path: "/", path: '/',
component: Layout, component: Layout,
redirect: "/index", redirect: '/index',
meta: { meta: {
title: "首页", title: '首页',
icon: "home-4-line", icon: 'home-4-line',
affix: true, affix: true,
}, },
children: [ children: [
{ {
path: "index", path: 'index',
name: "Index", name: 'Index',
component: () => import("@/views/index"), component: () => import('@/views/index'),
meta: { meta: {
title: "首页", title: '首页',
icon: "home-4-line", icon: 'home-4-line',
affix: true, affix: true,
}, },
}, },
], ],
}, },
{ {
path: "/vab", path: '/vab',
component: Layout, component: Layout,
redirect: "/vab/table", redirect: '/vab/table',
alwaysShow: true, alwaysShow: true,
meta: { meta: {
title: "组件", title: '组件',
icon: "apps-line", icon: 'apps-line',
}, },
children: [ children: [
{ {
path: "table", path: 'table',
name: "Table", name: 'Table',
component: () => import("@/views/vab/table"), component: () => import('@/views/vab/table'),
meta: { meta: {
title: "表格", title: '表格',
icon: "table-2", icon: 'table-2',
}, },
}, },
], ],
}, },
{ {
path: "/test", path: '/test',
component: Layout, component: Layout,
redirect: "/test/test", redirect: '/test/test',
meta: { meta: {
title: "动态路由测试", title: '动态路由测试',
icon: "test-tube-line", icon: 'test-tube-line',
}, },
children: [ children: [
{ {
path: "test", path: 'test',
name: "Test", name: 'Test',
component: () => import("@/views/test"), component: () => import('@/views/test'),
meta: { meta: {
title: "动态路由测试", title: '动态路由测试',
icon: "test-tube-line", icon: 'test-tube-line',
}, },
}, },
], ],
}, },
{ {
path: "/error", path: '/error',
name: "Error", name: 'Error',
component: Layout, component: Layout,
redirect: "/error/403", redirect: '/error/403',
meta: { meta: {
title: "错误页", title: '错误页',
icon: "error-warning-line", icon: 'error-warning-line',
}, },
children: [ children: [
{ {
path: "403", path: '403',
name: "Error403", name: 'Error403',
component: () => import("@/views/403"), component: () => import('@/views/403'),
meta: { meta: {
title: "403", title: '403',
icon: "error-warning-line", icon: 'error-warning-line',
}, },
}, },
{ {
path: "404", path: '404',
name: "Error404", name: 'Error404',
component: () => import("@/views/404"), component: () => import('@/views/404'),
meta: { meta: {
title: "404", title: '404',
icon: "error-warning-line", icon: 'error-warning-line',
}, },
}, },
], ],
}, },
{ {
path: "/*", path: '/*',
redirect: "/404", redirect: '/404',
hidden: true, hidden: true,
}, },
]; ]
const router = createRouter({ const router = createRouter({
history: createWebHashHistory(), history: createWebHashHistory(),
routes: constantRoutes, routes: constantRoutes,
}); })
export default router; export default router

View File

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

View File

@ -2,32 +2,32 @@ const state = {
admin: false, admin: false,
role: [], role: [],
ability: [], ability: [],
}; }
const getters = { const getters = {
admin: (state) => state.admin, admin: (state) => state.admin,
role: (state) => state.role, role: (state) => state.role,
ability: (state) => state.ability, ability: (state) => state.ability,
}; }
const mutations = { const mutations = {
setFull(state, admin) { setFull(state, admin) {
state.admin = admin; state.admin = admin
}, },
setRole(state, role) { setRole(state, role) {
state.role = role; state.role = role
}, },
setAbility(state, ability) { setAbility(state, ability) {
state.ability = ability; state.ability = ability
}, },
}; }
const actions = { const actions = {
setFull({ commit }, admin) { setFull({ commit }, admin) {
commit("setFull", admin); commit('setFull', admin)
}, },
setRole({ commit }, role) { setRole({ commit }, role) {
commit("setRole", role); commit('setRole', role)
}, },
setAbility({ commit }, ability) { 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 * @author chuzhixin 1204505056@qq.com
* @description 路由拦截状态管理目前两种模式all模式与intelligence模式其中partialRoutes是菜单暂未使用 * @description 路由拦截状态管理目前两种模式all模式与intelligence模式其中partialRoutes是菜单暂未使用
*/ */
import { asyncRoutes, constantRoutes } from "@/router"; import { asyncRoutes, constantRoutes } from '@/router'
import { getRouterList } from "@/api/router"; import { getRouterList } from '@/api/router'
import { convertRouter, filterRoutes } from "@/utils/routes"; import { convertRouter, filterRoutes } from '@/utils/routes'
const state = { routes: [], partialRoutes: [] }; const state = { routes: [], partialRoutes: [] }
const getters = { const getters = {
routes: (state) => state.routes, routes: (state) => state.routes,
partialRoutes: (state) => state.partialRoutes, partialRoutes: (state) => state.partialRoutes,
}; }
const mutations = { const mutations = {
setRoutes(state, routes) { setRoutes(state, routes) {
state.routes = routes; state.routes = routes
}, },
setPartialRoutes(state, routes) { setPartialRoutes(state, routes) {
state.partialRoutes = routes; state.partialRoutes = routes
}, },
}; }
const actions = { const actions = {
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -27,9 +27,9 @@ const actions = {
* @returns * @returns
*/ */
async setRoutes({ commit }) { async setRoutes({ commit }) {
const finallyRoutes = filterRoutes([...constantRoutes, ...asyncRoutes]); const finallyRoutes = filterRoutes([...constantRoutes, ...asyncRoutes])
commit("setRoutes", finallyRoutes); commit('setRoutes', finallyRoutes)
return [...asyncRoutes]; return [...asyncRoutes]
}, },
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -38,13 +38,13 @@ const actions = {
* @returns * @returns
*/ */
async setAllRoutes({ commit }) { async setAllRoutes({ commit }) {
let { data } = await getRouterList(); let { data } = await getRouterList()
if (data[data.length - 1].path !== "*") if (data[data.length - 1].path !== '*')
data.push({ path: "*", redirect: "/404", hidden: true }); data.push({ path: '*', redirect: '/404', hidden: true })
const asyncRoutes = convertRouter(data); const asyncRoutes = convertRouter(data)
const finallyRoutes = filterRoutes([...constantRoutes, ...asyncRoutes]); const finallyRoutes = filterRoutes([...constantRoutes, ...asyncRoutes])
commit("setRoutes", finallyRoutes); commit('setRoutes', finallyRoutes)
return [...asyncRoutes]; return [...asyncRoutes]
}, },
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -53,7 +53,7 @@ const actions = {
* @param accessedRoutes 画廊布局综合布局设置路由 * @param accessedRoutes 画廊布局综合布局设置路由
*/ */
setPartialRoutes({ commit }, 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 * @author chuzhixin 1204505056@qq.com
* @description 所有全局配置的状态管理如无必要请勿修改 * @description 所有全局配置的状态管理如无必要请勿修改
*/ */
import defaultSettings from "@/config"; import defaultSettings from '@/config'
import { isJson } from "@/utils/validate"; import { isJson } from '@/utils/validate'
const { const {
logo, logo,
@ -20,23 +20,23 @@ const {
showTagsBar, showTagsBar,
showNotice, showNotice,
showFullScreen, showFullScreen,
} = defaultSettings; } = defaultSettings
const getLocalStorage = (key) => { const getLocalStorage = (key) => {
const value = localStorage.getItem(key); const value = localStorage.getItem(key)
if (isJson(value)) { if (isJson(value)) {
return JSON.parse(value); return JSON.parse(value)
} else { } else {
return false; return false
} }
}; }
const theme = getLocalStorage("vue-admin-beautiful-pro-theme"); const theme = getLocalStorage('vue-admin-beautiful-pro-theme')
const { collapse } = getLocalStorage("vue-admin-beautiful-pro-collapse"); const { collapse } = getLocalStorage('vue-admin-beautiful-pro-collapse')
const { language } = getLocalStorage("vue-admin-beautiful-pro-language"); const { language } = getLocalStorage('vue-admin-beautiful-pro-language')
const toggleBoolean = (key) => { const toggleBoolean = (key) => {
return typeof theme[key] !== "undefined" ? theme[key] : key; return typeof theme[key] !== 'undefined' ? theme[key] : key
}; }
const state = { const state = {
logo, logo,
@ -45,7 +45,7 @@ const state = {
themeName: theme.themeName || themeName, themeName: theme.themeName || themeName,
layout: theme.layout || layout, layout: theme.layout || layout,
header: theme.header || header, header: theme.header || header,
device: "desktop", device: 'desktop',
language: language || i18n, language: language || i18n,
showLanguage: toggleBoolean(showLanguage), showLanguage: toggleBoolean(showLanguage),
showProgressBar: toggleBoolean(showProgressBar), showProgressBar: toggleBoolean(showProgressBar),
@ -55,7 +55,7 @@ const state = {
showTagsBar: toggleBoolean(showTagsBar), showTagsBar: toggleBoolean(showTagsBar),
showNotice: toggleBoolean(showNotice), showNotice: toggleBoolean(showNotice),
showFullScreen: toggleBoolean(showFullScreen), showFullScreen: toggleBoolean(showFullScreen),
}; }
const getters = { const getters = {
collapse: (state) => state.collapse, collapse: (state) => state.collapse,
device: (state) => state.device, device: (state) => state.device,
@ -73,107 +73,107 @@ const getters = {
showNotice: (state) => state.showNotice, showNotice: (state) => state.showNotice,
showFullScreen: (state) => state.showFullScreen, showFullScreen: (state) => state.showFullScreen,
themeName: (state) => state.themeName, themeName: (state) => state.themeName,
}; }
const mutations = { const mutations = {
toggleCollapse(state) { toggleCollapse(state) {
state.collapse = !state.collapse; state.collapse = !state.collapse
localStorage.setItem( localStorage.setItem(
"vue-admin-beautiful-pro-collapse", 'vue-admin-beautiful-pro-collapse',
`{"collapse":${state.collapse}}` `{"collapse":${state.collapse}}`
); )
}, },
toggleDevice(state, device) { toggleDevice(state, device) {
state.device = device; state.device = device
}, },
changeHeader(state, header) { changeHeader(state, header) {
state.header = header; state.header = header
}, },
changeLayout(state, layout) { changeLayout(state, layout) {
state.layout = layout; state.layout = layout
}, },
handleShowLanguage(state, showLanguage) { handleShowLanguage(state, showLanguage) {
state.showLanguage = showLanguage; state.showLanguage = showLanguage
}, },
handleShowProgressBar(state, showProgressBar) { handleShowProgressBar(state, showProgressBar) {
state.showProgressBar = showProgressBar; state.showProgressBar = showProgressBar
}, },
handleShowRefresh(state, showRefresh) { handleShowRefresh(state, showRefresh) {
state.showRefresh = showRefresh; state.showRefresh = showRefresh
}, },
handleShowSearch(state, showSearch) { handleShowSearch(state, showSearch) {
state.showSearch = showSearch; state.showSearch = showSearch
}, },
handleShowTheme(state, showTheme) { handleShowTheme(state, showTheme) {
state.showTheme = showTheme; state.showTheme = showTheme
}, },
handleShowTagsBar(state, showTagsBar) { handleShowTagsBar(state, showTagsBar) {
state.showTagsBar = showTagsBar; state.showTagsBar = showTagsBar
}, },
handleShowNotice(state, showNotice) { handleShowNotice(state, showNotice) {
state.showNotice = showNotice; state.showNotice = showNotice
}, },
handleShowFullScreen(state, showFullScreen) { handleShowFullScreen(state, showFullScreen) {
state.showFullScreen = showFullScreen; state.showFullScreen = showFullScreen
}, },
openSideBar(state) { openSideBar(state) {
state.collapse = false; state.collapse = false
}, },
foldSideBar(state) { foldSideBar(state) {
state.collapse = true; state.collapse = true
}, },
changeLanguage(state, language) { changeLanguage(state, language) {
localStorage.setItem( localStorage.setItem(
"vue-admin-beautiful-pro-language", 'vue-admin-beautiful-pro-language',
`{"language":"${language}"}` `{"language":"${language}"}`
); )
state.language = language; state.language = language
}, },
}; }
const actions = { const actions = {
toggleCollapse({ commit }) { toggleCollapse({ commit }) {
commit("toggleCollapse"); commit('toggleCollapse')
}, },
toggleDevice({ commit }, device) { toggleDevice({ commit }, device) {
commit("toggleDevice", device); commit('toggleDevice', device)
}, },
changeHeader({ commit }, header) { changeHeader({ commit }, header) {
commit("changeHeader", header); commit('changeHeader', header)
}, },
changeLayout({ commit }, layout) { changeLayout({ commit }, layout) {
commit("changeLayout", layout); commit('changeLayout', layout)
}, },
handleShowLanguage: ({ commit }, showLanguage) => { handleShowLanguage: ({ commit }, showLanguage) => {
commit("handleShowLanguage", showLanguage); commit('handleShowLanguage', showLanguage)
}, },
handleShowProgressBar: ({ commit }, showProgressBar) => { handleShowProgressBar: ({ commit }, showProgressBar) => {
commit("handleShowProgressBar", showProgressBar); commit('handleShowProgressBar', showProgressBar)
}, },
handleShowRefresh: ({ commit }, showRefresh) => { handleShowRefresh: ({ commit }, showRefresh) => {
commit("handleShowRefresh", showRefresh); commit('handleShowRefresh', showRefresh)
}, },
handleShowSearch: ({ commit }, showSearch) => { handleShowSearch: ({ commit }, showSearch) => {
commit("handleShowSearch", showSearch); commit('handleShowSearch', showSearch)
}, },
handleShowTheme: ({ commit }, showTheme) => { handleShowTheme: ({ commit }, showTheme) => {
commit("handleShowTheme", showTheme); commit('handleShowTheme', showTheme)
}, },
handleShowTagsBar({ commit }, showTagsBar) { handleShowTagsBar({ commit }, showTagsBar) {
commit("handleShowTagsBar", showTagsBar); commit('handleShowTagsBar', showTagsBar)
}, },
handleShowNotice: ({ commit }, showNotice) => { handleShowNotice: ({ commit }, showNotice) => {
commit("handleShowNotice", showNotice); commit('handleShowNotice', showNotice)
}, },
handleShowFullScreen: ({ commit }, showFullScreen) => { handleShowFullScreen: ({ commit }, showFullScreen) => {
commit("handleShowFullScreen", showFullScreen); commit('handleShowFullScreen', showFullScreen)
}, },
openSideBar({ commit }) { openSideBar({ commit }) {
commit("openSideBar"); commit('openSideBar')
}, },
foldSideBar({ commit }) { foldSideBar({ commit }) {
commit("foldSideBar"); commit('foldSideBar')
}, },
changeLanguage: ({ commit }, language) => { 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 = { const state = {
visitedRoutes: [], visitedRoutes: [],
}; }
const getters = { const getters = {
visitedRoutes: (state) => state.visitedRoutes, visitedRoutes: (state) => state.visitedRoutes,
}; }
const mutations = { const mutations = {
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -18,12 +18,12 @@ const mutations = {
* @returns * @returns
*/ */
addVisitedRoute(state, route) { 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 (target) {
if (route.fullPath !== target.fullPath) Object.assign(target, route); if (route.fullPath !== target.fullPath) Object.assign(target, route)
return; return
} }
state.visitedRoutes.push(Object.assign({}, route)); state.visitedRoutes.push(Object.assign({}, route))
}, },
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -34,8 +34,8 @@ const mutations = {
*/ */
delVisitedRoute(state, route) { delVisitedRoute(state, route) {
state.visitedRoutes.forEach((item, index) => { 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 * @author chuzhixin 1204505056@qq.com
@ -47,7 +47,7 @@ const mutations = {
delOthersVisitedRoutes(state, route) { delOthersVisitedRoutes(state, route) {
state.visitedRoutes = state.visitedRoutes.filter( state.visitedRoutes = state.visitedRoutes.filter(
(item) => item.meta.affix || item.path === route.path (item) => item.meta.affix || item.path === route.path
); )
}, },
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -57,11 +57,11 @@ const mutations = {
* @returns * @returns
*/ */
delLeftVisitedRoutes(state, route) { delLeftVisitedRoutes(state, route) {
let index = state.visitedRoutes.length; let index = state.visitedRoutes.length
state.visitedRoutes = state.visitedRoutes.filter((item) => { state.visitedRoutes = state.visitedRoutes.filter((item) => {
if (item.name === route.name) index = state.visitedRoutes.indexOf(item); if (item.name === route.name) index = state.visitedRoutes.indexOf(item)
return item.meta.affix || index <= state.visitedRoutes.indexOf(item); return item.meta.affix || index <= state.visitedRoutes.indexOf(item)
}); })
}, },
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -71,11 +71,11 @@ const mutations = {
* @returns * @returns
*/ */
delRightVisitedRoutes(state, route) { delRightVisitedRoutes(state, route) {
let index = state.visitedRoutes.length; let index = state.visitedRoutes.length
state.visitedRoutes = state.visitedRoutes.filter((item) => { state.visitedRoutes = state.visitedRoutes.filter((item) => {
if (item.name === route.name) index = state.visitedRoutes.indexOf(item); if (item.name === route.name) index = state.visitedRoutes.indexOf(item)
return item.meta.affix || index >= state.visitedRoutes.indexOf(item); return item.meta.affix || index >= state.visitedRoutes.indexOf(item)
}); })
}, },
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -85,9 +85,9 @@ const mutations = {
* @returns * @returns
*/ */
delAllVisitedRoutes(state) { delAllVisitedRoutes(state) {
state.visitedRoutes = state.visitedRoutes.filter((item) => item.meta.affix); state.visitedRoutes = state.visitedRoutes.filter((item) => item.meta.affix)
}, },
}; }
const actions = { const actions = {
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -96,7 +96,7 @@ const actions = {
* @param {*} route * @param {*} route
*/ */
addVisitedRoute({ commit }, route) { addVisitedRoute({ commit }, route) {
commit("addVisitedRoute", route); commit('addVisitedRoute', route)
}, },
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -105,7 +105,7 @@ const actions = {
* @param {*} route * @param {*} route
*/ */
delVisitedRoute({ commit }, route) { delVisitedRoute({ commit }, route) {
commit("delVisitedRoute", route); commit('delVisitedRoute', route)
}, },
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -114,7 +114,7 @@ const actions = {
* @param {*} route * @param {*} route
*/ */
delOthersVisitedRoutes({ commit }, route) { delOthersVisitedRoutes({ commit }, route) {
commit("delOthersVisitedRoutes", route); commit('delOthersVisitedRoutes', route)
}, },
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -123,7 +123,7 @@ const actions = {
* @param {*} route * @param {*} route
*/ */
delLeftVisitedRoutes({ commit }, route) { delLeftVisitedRoutes({ commit }, route) {
commit("delLeftVisitedRoutes", route); commit('delLeftVisitedRoutes', route)
}, },
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -132,7 +132,7 @@ const actions = {
* @param {*} route * @param {*} route
*/ */
delRightVisitedRoutes({ commit }, route) { delRightVisitedRoutes({ commit }, route) {
commit("delRightVisitedRoutes", route); commit('delRightVisitedRoutes', route)
}, },
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -140,7 +140,7 @@ const actions = {
* @param {*} { commit } * @param {*} { commit }
*/ */
delAllVisitedRoutes({ 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 * @author chuzhixin 1204505056@qq.com
* @description 登录获取用户信息退出登录清除accessToken逻辑不建议修改 * @description 登录获取用户信息退出登录清除accessToken逻辑不建议修改
*/ */
import { getUserInfo, login, logout } from "@/api/user"; import { getUserInfo, login, logout } from '@/api/user'
import { import {
getAccessToken, getAccessToken,
removeAccessToken, removeAccessToken,
setAccessToken, setAccessToken,
} from "@/utils/accessToken"; } from '@/utils/accessToken'
import { title, tokenName } from "@/config"; import { title, tokenName } from '@/config'
import { message, notification } from "ant-design-vue"; import { message, notification } from 'ant-design-vue'
const state = { const state = {
accessToken: getAccessToken(), accessToken: getAccessToken(),
username: "", username: '',
avatar: "", avatar: '',
}; }
const getters = { const getters = {
accessToken: (state) => state.accessToken, accessToken: (state) => state.accessToken,
username: (state) => state.username, username: (state) => state.username,
avatar: (state) => state.avatar, avatar: (state) => state.avatar,
}; }
const mutations = { const mutations = {
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -29,8 +29,8 @@ const mutations = {
* @param {*} accessToken * @param {*} accessToken
*/ */
setAccessToken(state, accessToken) { setAccessToken(state, accessToken) {
state.accessToken = accessToken; state.accessToken = accessToken
setAccessToken(accessToken); setAccessToken(accessToken)
}, },
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -39,7 +39,7 @@ const mutations = {
* @param {*} username * @param {*} username
*/ */
setUsername(state, username) { setUsername(state, username) {
state.username = username; state.username = username
}, },
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -48,9 +48,9 @@ const mutations = {
* @param {*} avatar * @param {*} avatar
*/ */
setAvatar(state, avatar) { setAvatar(state, avatar) {
state.avatar = avatar; state.avatar = avatar
}, },
}; }
const actions = { const actions = {
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -58,12 +58,9 @@ const actions = {
* @param {*} { commit, dispatch } * @param {*} { commit, dispatch }
*/ */
setVirtualRoles({ commit, dispatch }) { setVirtualRoles({ commit, dispatch }) {
dispatch("acl/setFull", true, { root: true }); dispatch('acl/setFull', true, { root: true })
commit( commit('setAvatar', 'https://i.gtimg.cn/club/item/face/img/2/15922_100.gif')
"setAvatar", commit('setUsername', 'admin(未开启登录拦截)')
"https://i.gtimg.cn/club/item/face/img/2/15922_100.gif"
);
commit("setUsername", "admin(未开启登录拦截)");
}, },
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -72,27 +69,27 @@ const actions = {
* @param {*} userInfo * @param {*} userInfo
*/ */
async login({ commit }, userInfo) { async login({ commit }, userInfo) {
const { data } = await login(userInfo); const { data } = await login(userInfo)
const accessToken = data[tokenName]; const accessToken = data[tokenName]
if (accessToken) { if (accessToken) {
commit("setAccessToken", accessToken); commit('setAccessToken', accessToken)
const hour = new Date().getHours(); const hour = new Date().getHours()
const thisTime = const thisTime =
hour < 8 hour < 8
? "早上好" ? '早上好'
: hour <= 11 : hour <= 11
? "上午好" ? '上午好'
: hour <= 13 : hour <= 13
? "中午好" ? '中午好'
: hour < 18 : hour < 18
? "下午好" ? '下午好'
: "晚上好"; : '晚上好'
notification.open({ notification.open({
message: `欢迎登录${title}`, message: `欢迎登录${title}`,
description: `${thisTime}`, description: `${thisTime}`,
}); })
} else { } else {
message.error(`登录接口异常,未正确返回${tokenName}...`); message.error(`登录接口异常,未正确返回${tokenName}...`)
} }
}, },
/** /**
@ -102,20 +99,20 @@ const actions = {
* @returns * @returns
*/ */
async getUserInfo({ commit, dispatch, state }) { async getUserInfo({ commit, dispatch, state }) {
const { data } = await getUserInfo(state.accessToken); const { data } = await getUserInfo(state.accessToken)
if (!data) { if (!data) {
message.error(`验证失败,请重新登录...`); message.error(`验证失败,请重新登录...`)
return false; return false
} }
let { username, avatar, roles, ability } = data; let { username, avatar, roles, ability } = data
if (username && roles && Array.isArray(roles)) { if (username && roles && Array.isArray(roles)) {
dispatch("acl/setRole", roles, { root: true }); dispatch('acl/setRole', roles, { root: true })
if (ability && ability.length > 0) if (ability && ability.length > 0)
dispatch("acl/setAbility", ability, { root: true }); dispatch('acl/setAbility', ability, { root: true })
commit("setUsername", username); commit('setUsername', username)
commit("setAvatar", avatar); commit('setAvatar', avatar)
} else { } else {
message.error("用户信息接口异常"); message.error('用户信息接口异常')
} }
}, },
@ -125,8 +122,8 @@ const actions = {
* @param {*} { dispatch } * @param {*} { dispatch }
*/ */
async logout({ dispatch }) { async logout({ dispatch }) {
await logout(state.accessToken); await logout(state.accessToken)
await dispatch("resetAll"); await dispatch('resetAll')
}, },
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -134,18 +131,18 @@ const actions = {
* @param {*} { commit, dispatch } * @param {*} { commit, dispatch }
*/ */
async resetAll({ dispatch }) { async resetAll({ dispatch }) {
await dispatch("setAccessToken", ""); await dispatch('setAccessToken', '')
await dispatch("acl/setFull", false, { root: true }); await dispatch('acl/setFull', false, { root: true })
await dispatch("acl/setRole", [], { root: true }); await dispatch('acl/setRole', [], { root: true })
await dispatch("acl/setAbility", [], { root: true }); await dispatch('acl/setAbility', [], { root: true })
removeAccessToken(); removeAccessToken()
}, },
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
* @description 设置token * @description 设置token
*/ */
setAccessToken({ commit }, accessToken) { 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 { storage, tokenTableName } from '@/config'
import cookie from "js-cookie"; import cookie from 'js-cookie'
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -8,17 +8,17 @@ import cookie from "js-cookie";
*/ */
export function getAccessToken() { export function getAccessToken() {
if (storage) { if (storage) {
if ("localStorage" === storage) { if ('localStorage' === storage) {
return localStorage.getItem(tokenTableName); return localStorage.getItem(tokenTableName)
} else if ("sessionStorage" === storage) { } else if ('sessionStorage' === storage) {
return sessionStorage.getItem(tokenTableName); return sessionStorage.getItem(tokenTableName)
} else if ("cookie" === storage) { } else if ('cookie' === storage) {
return cookie.get(tokenTableName); return cookie.get(tokenTableName)
} else { } else {
return localStorage.getItem(tokenTableName); return localStorage.getItem(tokenTableName)
} }
} else { } else {
return localStorage.getItem(tokenTableName); return localStorage.getItem(tokenTableName)
} }
} }
@ -30,17 +30,17 @@ export function getAccessToken() {
*/ */
export function setAccessToken(accessToken) { export function setAccessToken(accessToken) {
if (storage) { if (storage) {
if ("localStorage" === storage) { if ('localStorage' === storage) {
return localStorage.setItem(tokenTableName, accessToken); return localStorage.setItem(tokenTableName, accessToken)
} else if ("sessionStorage" === storage) { } else if ('sessionStorage' === storage) {
return sessionStorage.setItem(tokenTableName, accessToken); return sessionStorage.setItem(tokenTableName, accessToken)
} else if ("cookie" === storage) { } else if ('cookie' === storage) {
return cookie.set(tokenTableName, accessToken); return cookie.set(tokenTableName, accessToken)
} else { } else {
return localStorage.setItem(tokenTableName, accessToken); return localStorage.setItem(tokenTableName, accessToken)
} }
} else { } else {
return localStorage.setItem(tokenTableName, accessToken); return localStorage.setItem(tokenTableName, accessToken)
} }
} }
@ -51,16 +51,16 @@ export function setAccessToken(accessToken) {
*/ */
export function removeAccessToken() { export function removeAccessToken() {
if (storage) { if (storage) {
if ("localStorage" === storage) { if ('localStorage' === storage) {
return localStorage.removeItem(tokenTableName); return localStorage.removeItem(tokenTableName)
} else if ("sessionStorage" === storage) { } else if ('sessionStorage' === storage) {
return sessionStorage.clear(); return sessionStorage.clear()
} else if ("cookie" === storage) { } else if ('cookie' === storage) {
return cookie.remove(tokenTableName); return cookie.remove(tokenTableName)
} else { } else {
return localStorage.removeItem(tokenTableName); return localStorage.removeItem(tokenTableName)
} }
} else { } 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) { 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) if (value instanceof Array && value.length > 0)
return can(store.getters["acl/role"], { return can(store.getters['acl/role'], {
role: value, role: value,
mode: "oneOf", mode: 'oneOf',
}); })
let mode = "oneOf"; let mode = 'oneOf'
if (Object.prototype.hasOwnProperty.call(value, "mode")) mode = value["mode"]; if (Object.prototype.hasOwnProperty.call(value, 'mode')) mode = value['mode']
let result = true; let result = true
if (Object.prototype.hasOwnProperty.call(value, "role")) if (Object.prototype.hasOwnProperty.call(value, 'role'))
result = result =
result && can(store.getters["acl/role"], { role: value["role"], mode }); result && can(store.getters['acl/role'], { role: value['role'], mode })
if (result && Object.prototype.hasOwnProperty.call(value, "ability")) if (result && Object.prototype.hasOwnProperty.call(value, 'ability'))
result = result =
result && result &&
can(store.getters["acl/ability"], { can(store.getters['acl/ability'], {
role: value["ability"], role: value['ability'],
mode, mode,
}); })
return result; return result
} }
export function can(roleOrAbility, value) { export function can(roleOrAbility, value) {
let hasRole = false; let hasRole = false
if ( if (
value instanceof Object && value instanceof Object &&
Object.prototype.hasOwnProperty.call(value, "role") && Object.prototype.hasOwnProperty.call(value, 'role') &&
Object.prototype.hasOwnProperty.call(value, "mode") Object.prototype.hasOwnProperty.call(value, 'mode')
) { ) {
const { role, mode } = value; const { role, mode } = value
if (mode === "allOf") { if (mode === 'allOf') {
hasRole = role.every((item) => { hasRole = role.every((item) => {
return roleOrAbility.includes(item); return roleOrAbility.includes(item)
}); })
} }
if (mode === "oneOf") { if (mode === 'oneOf') {
hasRole = role.some((item) => { hasRole = role.some((item) => {
return roleOrAbility.includes(item); return roleOrAbility.includes(item)
}); })
} }
if (mode === "except") { if (mode === 'except') {
hasRole = !role.some((item) => { 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"; import { devDependencies } from '../../package.json'
if (!devDependencies["vab-config"]) document.body.innerHTML = ""; if (!devDependencies['vab-config']) document.body.innerHTML = ''
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
* @description 格式化时间 * @description 格式化时间
@ -9,20 +9,20 @@ if (!devDependencies["vab-config"]) document.body.innerHTML = "";
*/ */
export function parseTime(time, cFormat) { export function parseTime(time, cFormat) {
if (arguments.length === 0) { if (arguments.length === 0) {
return null; return null
} }
const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}"; const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date; let date
if (typeof time === "object") { if (typeof time === 'object') {
date = time; date = time
} else { } else {
if (typeof time === "string" && /^[0-9]+$/.test(time)) { if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
time = parseInt(time); time = parseInt(time)
} }
if (typeof time === "number" && time.toString().length === 10) { if (typeof time === 'number' && time.toString().length === 10) {
time = time * 1000; time = time * 1000
} }
date = new Date(time); date = new Date(time)
} }
const formatObj = { const formatObj = {
y: date.getFullYear(), y: date.getFullYear(),
@ -32,17 +32,17 @@ export function parseTime(time, cFormat) {
i: date.getMinutes(), i: date.getMinutes(),
s: date.getSeconds(), s: date.getSeconds(),
a: date.getDay(), a: date.getDay(),
}; }
return format.replace(/{([ymdhisa])+}/g, (result, key) => { return format.replace(/{([ymdhisa])+}/g, (result, key) => {
let value = formatObj[key]; let value = formatObj[key]
if (key === "a") { if (key === 'a') {
return ["日", "一", "二", "三", "四", "五", "六"][value]; return ['日', '一', '二', '三', '四', '五', '六'][value]
} }
if (result.length > 0 && value < 10) { 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} * @returns {string}
*/ */
export function formatTime(time, option) { export function formatTime(time, option) {
if (("" + time).length === 10) { if (('' + time).length === 10) {
time = parseInt(time) * 1000; time = parseInt(time) * 1000
} else { } else {
time = +time; time = +time
} }
const d = new Date(time); const d = new Date(time)
const now = Date.now(); const now = Date.now()
const diff = (now - d) / 1000; const diff = (now - d) / 1000
if (diff < 30) { if (diff < 30) {
return "刚刚"; return '刚刚'
} else if (diff < 3600) { } else if (diff < 3600) {
// less 1 hour // less 1 hour
return Math.ceil(diff / 60) + "分钟前"; return Math.ceil(diff / 60) + '分钟前'
} else if (diff < 3600 * 24) { } else if (diff < 3600 * 24) {
return Math.ceil(diff / 3600) + "小时前"; return Math.ceil(diff / 3600) + '小时前'
} else if (diff < 3600 * 24 * 2) { } else if (diff < 3600 * 24 * 2) {
return "1天前"; return '1天前'
} }
if (option) { if (option) {
return parseTime(time, option); return parseTime(time, option)
} else { } else {
return ( return (
d.getMonth() + d.getMonth() +
1 + 1 +
"月" + '月' +
d.getDate() + d.getDate() +
"日" + '日' +
d.getHours() + d.getHours() +
"时" + '时' +
d.getMinutes() + d.getMinutes() +
"分" '分'
); )
} }
} }
@ -97,9 +97,9 @@ export function formatTime(time, option) {
* @returns {{}|any} * @returns {{}|any}
*/ */
export function paramObj(url) { export function paramObj(url) {
const search = url.split("?")[1]; const search = url.split('?')[1]
if (!search) { if (!search) {
return {}; return {}
} }
return JSON.parse( return JSON.parse(
'{"' + '{"' +
@ -107,9 +107,9 @@ export function paramObj(url) {
.replace(/"/g, '\\"') .replace(/"/g, '\\"')
.replace(/&/g, '","') .replace(/&/g, '","')
.replace(/=/g, '":"') .replace(/=/g, '":"')
.replace(/\+/g, " ") + .replace(/\+/g, ' ') +
'"}' '"}'
); )
} }
/** /**
@ -120,27 +120,27 @@ export function paramObj(url) {
*/ */
export function translateDataToTree(data) { export function translateDataToTree(data) {
const parent = data.filter( const parent = data.filter(
(value) => value.parentId === "undefined" || value.parentId == null (value) => value.parentId === 'undefined' || value.parentId == null
); )
const children = data.filter( const children = data.filter(
(value) => value.parentId !== "undefined" && value.parentId != null (value) => value.parentId !== 'undefined' && value.parentId != null
); )
const translator = (parent, children) => { const translator = (parent, children) => {
parent.forEach((parent) => { parent.forEach((parent) => {
children.forEach((current, index) => { children.forEach((current, index) => {
if (current.parentId === parent.id) { if (current.parentId === parent.id) {
const temp = JSON.parse(JSON.stringify(children)); const temp = JSON.parse(JSON.stringify(children))
temp.splice(index, 1); temp.splice(index, 1)
translator([current], temp); translator([current], temp)
typeof parent.children !== "undefined" typeof parent.children !== 'undefined'
? parent.children.push(current) ? parent.children.push(current)
: (parent.children = [current]); : (parent.children = [current])
} }
}); })
}); })
}; }
translator(parent, children); translator(parent, children)
return parent; return parent
} }
/** /**
@ -150,24 +150,24 @@ export function translateDataToTree(data) {
* @returns {[]} * @returns {[]}
*/ */
export function translateTreeToData(data) { export function translateTreeToData(data) {
const result = []; const result = []
data.forEach((item) => { data.forEach((item) => {
const loop = (data) => { const loop = (data) => {
result.push({ result.push({
id: data.id, id: data.id,
name: data.name, name: data.name,
parentId: data.parentId, parentId: data.parentId,
}); })
const child = data.children; const child = data.children
if (child) { if (child) {
for (let i = 0; i < child.length; i++) { for (let i = 0; i < child.length; i++) {
loop(child[i]); loop(child[i])
} }
} }
}; }
loop(item); loop(item)
}); })
return result; return result
} }
/** /**
@ -177,19 +177,19 @@ export function translateTreeToData(data) {
* @returns {string} * @returns {string}
*/ */
export function tenBitTimestamp(time) { export function tenBitTimestamp(time) {
const date = new Date(time * 1000); const date = new Date(time * 1000)
const y = date.getFullYear(); const y = date.getFullYear()
let m = date.getMonth() + 1; let m = date.getMonth() + 1
m = m < 10 ? "" + m : m; m = m < 10 ? '' + m : m
let d = date.getDate(); let d = date.getDate()
d = d < 10 ? "" + d : d; d = d < 10 ? '' + d : d
let h = date.getHours(); let h = date.getHours()
h = h < 10 ? "0" + h : h; h = h < 10 ? '0' + h : h
let minute = date.getMinutes(); let minute = date.getMinutes()
let second = date.getSeconds(); let second = date.getSeconds()
minute = minute < 10 ? "0" + minute : minute; minute = minute < 10 ? '0' + minute : minute
second = second < 10 ? "0" + second : second; second = second < 10 ? '0' + second : second
return y + "年" + m + "月" + d + "日 " + h + ":" + minute + ":" + second; //组合 return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second //组合
} }
/** /**
@ -199,19 +199,19 @@ export function tenBitTimestamp(time) {
* @returns {string} * @returns {string}
*/ */
export function thirteenBitTimestamp(time) { export function thirteenBitTimestamp(time) {
const date = new Date(time / 1); const date = new Date(time / 1)
const y = date.getFullYear(); const y = date.getFullYear()
let m = date.getMonth() + 1; let m = date.getMonth() + 1
m = m < 10 ? "" + m : m; m = m < 10 ? '' + m : m
let d = date.getDate(); let d = date.getDate()
d = d < 10 ? "" + d : d; d = d < 10 ? '' + d : d
let h = date.getHours(); let h = date.getHours()
h = h < 10 ? "0" + h : h; h = h < 10 ? '0' + h : h
let minute = date.getMinutes(); let minute = date.getMinutes()
let second = date.getSeconds(); let second = date.getSeconds()
minute = minute < 10 ? "0" + minute : minute; minute = minute < 10 ? '0' + minute : minute
second = second < 10 ? "0" + second : second; second = second < 10 ? '0' + second : second
return y + "年" + m + "月" + d + "日 " + h + ":" + minute + ":" + second; //组合 return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second //组合
} }
/** /**
@ -221,12 +221,12 @@ export function thirteenBitTimestamp(time) {
* @returns {string} * @returns {string}
*/ */
export function uuid(length = 32) { export function uuid(length = 32) {
const num = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; const num = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
let str = ""; let str = ''
for (let i = 0; i < length; i++) { 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} * @returns {number}
*/ */
export function random(m, n) { 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 () { export const on = (function () {
return function (element, event, handler, useCapture = false) { return function (element, event, handler, useCapture = false) {
if (element && event && handler) { if (element && event && handler) {
element.addEventListener(event, handler, useCapture); element.addEventListener(event, handler, useCapture)
} }
}; }
})(); })()
/** /**
* @author chuzhixin 1204505056@qq.com * @author chuzhixin 1204505056@qq.com
@ -261,7 +261,7 @@ export const on = (function () {
export const off = (function () { export const off = (function () {
return function (element, event, handler, useCapture = false) { return function (element, event, handler, useCapture = false) {
if (element && event) { 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 * @author chuzhixin 1204505056@qq.com
@ -7,9 +7,9 @@ import { title, titleReverse, titleSeparator } from "@/config";
* @returns {string} * @returns {string}
*/ */
export default function getPageTitle(pageTitle) { export default function getPageTitle(pageTitle) {
let newTitles = []; let newTitles = []
if (pageTitle) newTitles.push(pageTitle); if (pageTitle) newTitles.push(pageTitle)
if (title) newTitles.push(title); if (title) newTitles.push(title)
if (titleReverse) newTitles = newTitles.reverse(); if (titleReverse) newTitles = newTitles.reverse()
return newTitles.join(titleSeparator); return newTitles.join(titleSeparator)
} }

View File

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

View File

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

View File

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

View File

@ -5,7 +5,7 @@
* @returns {boolean} * @returns {boolean}
*/ */
export function isExternal(path) { 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} * @returns {boolean}
*/ */
export function isPassword(value) { export function isPassword(value) {
return value.length >= 6; return value.length >= 6
} }
/** /**
@ -25,8 +25,8 @@ export function isPassword(value) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isNumber(value) { export function isNumber(value) {
const reg = /^[0-9]*$/; const reg = /^[0-9]*$/
return reg.test(value); return reg.test(value)
} }
/** /**
@ -36,8 +36,8 @@ export function isNumber(value) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isName(value) { export function isName(value) {
const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/; const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/
return reg.test(value); return reg.test(value)
} }
/** /**
@ -47,8 +47,8 @@ export function isName(value) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isIP(ip) { 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])$/; 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); return reg.test(ip)
} }
/** /**
@ -58,8 +58,8 @@ export function isIP(ip) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isUrl(url) { 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.,?'\\+&%$#=~_-]+))*$/; 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); return reg.test(url)
} }
/** /**
@ -69,8 +69,8 @@ export function isUrl(url) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isLowerCase(value) { export function isLowerCase(value) {
const reg = /^[a-z]+$/; const reg = /^[a-z]+$/
return reg.test(value); return reg.test(value)
} }
/** /**
@ -80,8 +80,8 @@ export function isLowerCase(value) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isUpperCase(value) { export function isUpperCase(value) {
const reg = /^[A-Z]+$/; const reg = /^[A-Z]+$/
return reg.test(value); return reg.test(value)
} }
/** /**
@ -91,8 +91,8 @@ export function isUpperCase(value) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isAlphabets(value) { export function isAlphabets(value) {
const reg = /^[A-Za-z]+$/; const reg = /^[A-Za-z]+$/
return reg.test(value); return reg.test(value)
} }
/** /**
@ -102,7 +102,7 @@ export function isAlphabets(value) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isString(value) { 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} * @returns {arg is any[]|boolean}
*/ */
export function isArray(arg) { export function isArray(arg) {
if (typeof Array.isArray === "undefined") { if (typeof Array.isArray === 'undefined') {
return Object.prototype.toString.call(arg) === "[object Array]"; 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} * @returns {boolean}
*/ */
export function isPort(value) { 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])$/; 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); return reg.test(value)
} }
/** /**
@ -136,8 +136,8 @@ export function isPort(value) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isPhone(value) { export function isPhone(value) {
const reg = /^1\d{10}$/; const reg = /^1\d{10}$/
return reg.test(value); return reg.test(value)
} }
/** /**
@ -147,8 +147,8 @@ export function isPhone(value) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isIdCard(value) { 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]$/; 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); return reg.test(value)
} }
/** /**
@ -158,8 +158,8 @@ export function isIdCard(value) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isEmail(value) { export function isEmail(value) {
const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
return reg.test(value); return reg.test(value)
} }
/** /**
@ -169,8 +169,8 @@ export function isEmail(value) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isChina(value) { export function isChina(value) {
const reg = /^[\u4E00-\u9FA5]{2,4}$/; const reg = /^[\u4E00-\u9FA5]{2,4}$/
return reg.test(value); return reg.test(value)
} }
/** /**
@ -183,10 +183,10 @@ export function isBlank(value) {
return ( return (
value == null || value == null ||
false || false ||
value === "" || value === '' ||
value.trim() === "" || value.trim() === '' ||
value.toLocaleLowerCase().trim() === "null" value.toLocaleLowerCase().trim() === 'null'
); )
} }
/** /**
@ -196,8 +196,8 @@ export function isBlank(value) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isTel(value) { 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}))?$/; 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); return reg.test(value)
} }
/** /**
@ -207,8 +207,8 @@ export function isTel(value) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isNum(value) { export function isNum(value) {
const reg = /^\d+(\.\d{1,2})?$/; const reg = /^\d+(\.\d{1,2})?$/
return reg.test(value); return reg.test(value)
} }
/** /**
@ -218,8 +218,8 @@ export function isNum(value) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isLongitude(value) { 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})$/; 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); return reg.test(value)
} }
/** /**
@ -229,8 +229,8 @@ export function isLongitude(value) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isLatitude(value) { export function isLatitude(value) {
const reg = /^[-|+]?([0-8]?\d{1}\.\d{1,5}|90\.0{1,5})$/; const reg = /^[-|+]?([0-8]?\d{1}\.\d{1,5}|90\.0{1,5})$/
return reg.test(value); return reg.test(value)
} }
/** /**
@ -240,10 +240,10 @@ export function isLatitude(value) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isRTSP(value) { 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 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 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])\//; 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); return reg.test(value) || reg1.test(value) || reg2.test(value)
} }
/** /**
@ -253,16 +253,16 @@ export function isRTSP(value) {
* @returns {boolean} * @returns {boolean}
*/ */
export function isJson(value) { export function isJson(value) {
if (typeof value == "string") { if (typeof value == 'string') {
try { try {
var obj = JSON.parse(value); var obj = JSON.parse(value)
if (typeof obj == "object" && obj) { if (typeof obj == 'object' && obj) {
return true; return true
} else { } else {
return false; return false
} }
} catch (e) { } 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.keys().forEach((fileName) => {
requirePlugin(fileName); requirePlugin(fileName)
}); })

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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