vue动态路由数据库表设计
数据库表创建SQL
USE [CHMS]
GO
/****** Object: Table [dbo].[SysMenu] Script Date: 2021/5/5 23:09:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SysMenu](
[Id] [int] IDENTITY(10000,1) NOT NULL,
[Name] [nvarchar](32) NOT NULL,
[ParentId] [int] NULL,
[Path] [nvarchar](256) NOT NULL,
[Weight] [int] NOT NULL,
[ExtData] [text] NULL,
[UpdateTime] [bigint] NOT NULL,
[CreateTime] [bigint] NOT NULL,
[Updator] [varchar](16) NULL,
[Creator] [varchar](16) NOT NULL,
[Children] [text] NULL,
[Component] [nvarchar](256) NULL,
[Redirect] [nvarchar](256) NULL,
[Title] [nvarchar](50) NULL,
[Icon] [nvarchar](50) NULL,
[Hidden] [nvarchar](50) NULL,
[Tag] [nvarchar](50) NULL,
[Class_layer] [int] NULL,
[Action_type] [nvarchar](500) NULL,
[DyId] [nvarchar](50) NULL,
CONSTRAINT [PK_SysMenu] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[SysMenu] ADD CONSTRAINT [DF_SysMenu_Weight] DEFAULT ((0)) FOR [Weight]
GO
ALTER TABLE [dbo].[SysMenu] ADD CONSTRAINT [DF_SysMenu_UpdateTime] DEFAULT ((0)) FOR [UpdateTime]
GO
ALTER TABLE [dbo].[SysMenu] ADD CONSTRAINT [DF_SysMenu_CreateTime] DEFAULT ((0)) FOR [CreateTime]
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'数据ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'Id'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'路由名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'父级数据ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'ParentId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'路由地址' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'Path'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'排序权重' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'Weight'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'扩展数据' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'ExtData'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'更新时间(JS时间戳)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'UpdateTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'创建时间(JS时间戳)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'CreateTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'更新人用户名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'Updator'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'创建人用户名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'Creator'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'嵌套子类' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'Children'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'组件地址' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'Component'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'跳转' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'Redirect'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'标题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'图片' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'Icon'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否隐藏' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'Hidden'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'显示名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'Tag'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'层级' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'Class_layer'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'权限集合' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'Action_type'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'调用ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu', @level2type=N'COLUMN',@level2name=N'DyId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'系统菜单' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SysMenu'
GO
vue前端加载路由
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { getItemsByRoleId, getItemsByPid } from '@/api/sys-menu'
import { FlatToNestedRoutes } from '@/utils'
import { getItem as getRoleItem } from '@/api/sys-role'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
router.beforeEach(async(to, from, next) => {
// start progress bar
NProgress.start()
// set page title
document.title = getPageTitle(to.meta.title)
// determine whether the user has logged in
const hasToken = getToken()
if (hasToken) {
if (to.path === '/login') {
// if is logged in, redirect to the home page
next({ path: '/' })
NProgress.done()
} else {
// determine whether the user has obtained his permission roles through getInfo
const hasRoles = store.getters.permission_routes && store.getters.permission_routes.length > 0
// console.log('permission_routes=' + JSON.stringify(store.getters.permission_routes))
if (hasRoles) {
next()
} else {
try {
// get user info
// note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
const info = await store.dispatch('user/getInfo')
// generate accessible routes map based on roles
// const accessRoutes = await store.dispatch('permission/generateRoutes', info.roles)
// // dynamically add accessible routes
// router.addRoutes(accessRoutes)
// hack method to ensure that addRoutes is complete
// set the replace: true, so the navigation will not leave a history record
var roleType = null
await getRoleItem(info.RoleId).then(resp => {
roleType = resp.data.Data.RoleType
})
if (roleType === '1') { // 超级管理员可以查看所有菜单 'Hidden=\'false\''
await getItemsByPid(null, ' Class_layer, Weight').then(resp => {
var data = resp.data.Data
var menusTemp = FlatToNestedRoutes(data)
store.dispatch('permission/generateRoutes', menusTemp)
router.addRoutes(menusTemp)
})
} else {
await getItemsByRoleId(info.RoleId, 'Show').then(resp => {
var data = resp.data.Data
var menusTemp = FlatToNestedRoutes(data)
store.dispatch('permission/generateRoutes', menusTemp)
router.addRoutes(menusTemp)
})
}
next({ ...to, replace: true })
} catch (error) {
// remove token and go to login page to re-login
await store.dispatch('user/resetToken')
Message.error(error || 'Has Error')
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
}
} else {
/* has no token*/
if (whiteList.indexOf(to.path) !== -1) {
// in the free login whitelist, go directly
next()
} else {
// other pages that do not have permission to access are redirected to the login page.
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
})
router.afterEach(() => {
// finish progress bar
NProgress.done()
})
import Layout from '@/layout'
/**
* Created by PanJiaChen on 16/11/18.
*/
const crypto = require('crypto')
export function getPreMonth(date) {
var arr = parseTime(date,"{y}-{m}-{d}").split('-');
var year = arr[0]; //获取当前日期的年份
var month = arr[1]; //获取当前日期的月份
var day = arr[2]; //获取当前日期的日
var days = new Date(year, month, 0);
days = days.getDate(); //获取当前日期中月的天数
var year2 = year;
var month2 = parseInt(month) - 1;
if (month2 == 0) {
year2 = parseInt(year2) - 1;
month2 = 12;
}
var day2 = day;
var days2 = new Date(year2, month2, 0);
days2 = days2.getDate();
if (day2 > days2) {
day2 = days2;
}
if (month2 < 10) {
month2 = '0' + month2;
}
var t2 = year2 + '-' + month2 + '-' + 1;
return parseTime(t2,"{y}-{m}-{d}");
}
/**
* Parse the time to string
* @param {(Object|string|number)} time
* @param {string} cFormat
* @returns {string}
*/
export function parseTime(time, cFormat) {
if (time === null) {
return null
}
if (time === 0) {
return null
}
if (arguments.length === 0) {
return null
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
time = parseInt(time)
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value]
}
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}
/**
* @param {number} time
* @param {string} option
* @returns {string}
*/
export function formatTime(time, option) {
if (('' + time).length === 10) {
time = parseInt(time) * 1000
} else {
time = +time
}
const d = new Date(time)
const now = Date.now()
const diff = (now - d) / 1000
if (diff < 30) {
return '刚刚'
} else if (diff < 3600) {
// less 1 hour
return Math.ceil(diff / 60) + '分钟前'
} else if (diff < 3600 * 24) {
return Math.ceil(diff / 3600) + '小时前'
} else if (diff < 3600 * 24 * 2) {
return '1天前'
}
if (option) {
return parseTime(time, option)
} else {
return (
d.getMonth() +
1 +
'月' +
d.getDate() +
'日' +
d.getHours() +
'时' +
d.getMinutes() +
'分'
)
}
}
/**
* @param {string} url
* @returns {Object}
*/
export function getQueryObject(url) {
url = url == null ? window.location.href : url
const search = url.substring(url.lastIndexOf('?') + 1)
const obj = {}
const reg = /([^?&=]+)=([^?&=]*)/g
search.replace(reg, (rs, $1, $2) => {
const name = decodeURIComponent($1)
let val = decodeURIComponent($2)
val = String(val)
obj[name] = val
return rs
})
return obj
}
/**
* @param {string} input value
* @returns {number} output value
*/
export function byteLength(str) {
// returns the byte length of an utf8 string
let s = str.length
for (var i = str.length - 1; i >= 0; i--) {
const code = str.charCodeAt(i)
if (code > 0x7f && code <= 0x7ff) s++
else if (code > 0x7ff && code <= 0xffff) s += 2
if (code >= 0xDC00 && code <= 0xDFFF) i--
}
return s
}
/**
* @param {Array} actual
* @returns {Array}
*/
export function cleanArray(actual) {
const newArray = []
for (let i = 0; i < actual.length; i++) {
if (actual[i]) {
newArray.push(actual[i])
}
}
return newArray
}
/**
* @param {Object} json
* @returns {Array}
*/
export function param(json) {
if (!json) return ''
return cleanArray(
Object.keys(json).map(key => {
if (json[key] === undefined) return ''
return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
})
).join('&')
}
/**
* @param {string} url
* @returns {Object}
*/
export function param2Obj(url) {
const search = url.split('?')[1]
if (!search) {
return {}
}
return JSON.parse(
'{"' +
decodeURIComponent(search)
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"')
.replace(/\+/g, ' ') +
'"}'
)
}
/**
* @param {string} val
* @returns {string}
*/
export function html2Text(val) {
const div = document.createElement('div')
div.innerHTML = val
return div.textContent || div.innerText
}
/**
* Merges two objects, giving the last one precedence
* @param {Object} target
* @param {(Object|Array)} source
* @returns {Object}
*/
export function objectMerge(target, source) {
if (typeof target !== 'object') {
target = {}
}
if (Array.isArray(source)) {
return source.slice()
}
Object.keys(source).forEach(property => {
const sourceProperty = source[property]
if (typeof sourceProperty === 'object') {
target[property] = objectMerge(target[property], sourceProperty)
} else {
target[property] = sourceProperty
}
})
return target
}
//处理默认选中当前日期
export function getNowTime() {
var now = new Date();
var year = now.getFullYear(); //得到年份
var month = now.getMonth(); //得到月份
var date = now.getDate(); //得到日期
var hour = " 00:00:00"; //默认时分秒 如果传给后台的格式为年月日时分秒,就需要加这个,如若不需要,此行可忽略
month = month + 1;
month = month.toString().padStart(2, "0");
date = date.toString().padStart(2, "0");
var defaultDate = `${year}-${month}-${date}`;
return defaultDate;
}
/**
* @param {HTMLElement} element
* @param {string} className
*/
export function toggleClass(element, className) {
if (!element || !className) {
return
}
let classString = element.className
const nameIndex = classString.indexOf(className)
if (nameIndex === -1) {
classString += '' + className
} else {
classString =
classString.substr(0, nameIndex) +
classString.substr(nameIndex + className.length)
}
element.className = classString
}
/**
* @param {string} type
* @returns {Date}
*/
export function getTime(type) {
if (type === 'start') {
return new Date().getTime() - 3600 * 1000 * 24 * 90
} else {
return new Date(new Date().toDateString())
}
}
/**
* @param {Function} func
* @param {number} wait
* @param {boolean} immediate
* @return {*}
*/
export function debounce(func, wait, immediate) {
let timeout, args, context, timestamp, result
const later = function () {
// 据上一次触发时间间隔
const last = +new Date() - timestamp
// 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last)
} else {
timeout = null
// 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
if (!immediate) {
result = func.apply(context, args)
if (!timeout) context = args = null
}
}
}
return function (...args) {
context = this
timestamp = +new Date()
const callNow = immediate && !timeout
// 如果延时不存在,重新设定延时
if (!timeout) timeout = setTimeout(later, wait)
if (callNow) {
result = func.apply(context, args)
context = args = null
}
return result
}
}
/**
* This is just a simple version of deep copy
* Has a lot of edge cases bug
* If you want to use a perfect deep copy, use lodash's _.cloneDeep
* @param {Object} source
* @returns {Object}
*/
export function deepClone(source) {
if (!source && typeof source !== 'object') {
throw new Error('error arguments', 'deepClone')
}
const targetObj = source.constructor === Array ? [] : {}
Object.keys(source).forEach(keys => {
if (source[keys] && typeof source[keys] === 'object') {
targetObj[keys] = deepClone(source[keys])
} else {
targetObj[keys] = source[keys]
}
})
return targetObj
}
/**
* @param {Array} arr
* @returns {Array}
*/
export function uniqueArr(arr) {
return Array.from(new Set(arr))
}
/**
* @returns {string}
*/
export function createUniqueString() {
const timestamp = +new Date() + ''
const randomNum = parseInt((1 + Math.random()) * 65536) + ''
return (+(randomNum + timestamp)).toString(32)
}
/**
* Check if an element has a class
* @param {HTMLElement} elm
* @param {string} cls
* @returns {boolean}
*/
export function hasClass(ele, cls) {
return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}
/**
* Add class to element
* @param {HTMLElement} elm
* @param {string} cls
*/
export function addClass(ele, cls) {
if (!hasClass(ele, cls)) ele.className += ' ' + cls
}
/**
* Remove class from element
* @param {HTMLElement} elm
* @param {string} cls
*/
export function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
ele.className = ele.className.replace(reg, ' ')
}
}
export const datetimePickerOptions = [{
text: '今天',
onClick(picker) {
picker.$emit('pick', new Date())
}
},
{
text: '昨天',
onClick(picker) {
const date = new Date()
date.setTime(date.getTime() - 3600 * 1000 * 24 * 1)
picker.$emit('pick', date)
}
},
{
text: '一周前',
onClick(picker) {
const date = new Date()
date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
picker.$emit('pick', date)
}
},
{
text: '30天前',
onClick(picker) {
const date = new Date()
date.setTime(date.getTime() - 3600 * 1000 * 24 * 30)
picker.$emit('pick', date)
}
},
{
text: '90天前',
onClick(picker) {
const date = new Date()
date.setTime(date.getTime() - 3600 * 1000 * 24 * 90)
picker.$emit('pick', date)
}
}
]
export const datetimeAfterPickerOptions = [{
text: '今天',
onClick(picker) {
picker.$emit('pick', new Date())
}
},
{
text: '明天',
onClick(picker) {
const date = new Date()
date.setTime(date.getTime() + 3600 * 1000 * 24 * 1)
picker.$emit('pick', date)
}
},
{
text: '一周后',
onClick(picker) {
const date = new Date()
date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
picker.$emit('pick', date)
}
},
{
text: '30天后',
onClick(picker) {
const date = new Date()
date.setTime(date.getTime() + 3600 * 1000 * 24 * 30)
picker.$emit('pick', date)
}
},
{
text: '90天后',
onClick(picker) {
const date = new Date()
date.setTime(date.getTime() + 3600 * 1000 * 24 * 90)
picker.$emit('pick', date)
}
}
]
export const datetimeAfterNullablePickerOptions = [{
text: '不限期',
onClick(picker) {
picker.$emit('pick', new Date().setTime(0))
}
},
{
text: '今天',
onClick(picker) {
picker.$emit('pick', new Date())
}
},
{
text: '明天',
onClick(picker) {
const date = new Date()
date.setTime(date.getTime() + 3600 * 1000 * 24 * 1)
picker.$emit('pick', date)
}
},
{
text: '一周后',
onClick(picker) {
const date = new Date()
date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
picker.$emit('pick', date)
}
},
{
text: '30天后',
onClick(picker) {
const date = new Date()
date.setTime(date.getTime() + 3600 * 1000 * 24 * 30)
picker.$emit('pick', date)
}
},
{
text: '90天后',
onClick(picker) {
const date = new Date()
date.setTime(date.getTime() + 3600 * 1000 * 24 * 90)
picker.$emit('pick', date)
}
}
]
/**
* 获取指定文字的MD5值,使用UTF8编码
* @param {string} text 指定文字
* @returns {string} 文字的MD5值
*/
export function md5(text) {
return crypto.createHash('md5').update(text).digest('hex')
}
/**
* 格式化输出字节大小
* @param {String} bytes 字节数
* @param {Number} decimals 精度,默认2
*/
export function formatBytes(bytes, decimals) {
if (bytes === 0) return '0 Bytes'
const k = 1024
const dm = decimals || 2
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
}
/**
* 获取JavaScript时间戳
*/
export function js_time() {
return new Date().getTime()
}
/**
* 获取Unix时间戳
*/
export function unix_time() {
return parseInt(js_time() / 1000)
}
/**
* 输出GUID,默认没有短线,大写输出,32位
* @param {boolean} line 是否含有短线
* @param {boolean} upper 是否大写输出
*/
export function guid(line = false, upper = true) {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1)
}
var link = '-'
if (!line) {
link = ''
}
const g = s4() + s4() + link + s4() + link + s4() + link + s4() + link + s4() + s4() + s4()
return upper ? g.toUpperCase() : g
}
/**
* 拼接一个 and like 的SQL语句
* @param {string} name 字段名
* @param {string} value 匹配值
*/
export function andLike(name, value) {
return ` AND ${name} LIKE '%${value}%'`
}
/**
* 拼接一个 and 的SQL语句
* @param {string} name 字段名
* @param {string} value 匹配值
*/
export function AND(name, value) {
return ` AND ${name} = '${value}'`
}
/**
* @param {Object} json
* @returns {Array}
*/
export function IN(name, json, value) {
if (!json) return ''
var ar = cleanArray(
Object.keys(json).map(key => {
if (json[key] === undefined) return ''
return json[key][value] + ''
})
).join(',')
return ` AND ${name} in (${ar})`
}
export function IN2(name, json, value, value2) {
if (!json) return ''
var ar = cleanArray(
Object.keys(json).map(key => {
if (json[key] === undefined) return ''
return json[key][value][value2] + ''
})
).join(',')
return ` AND ${name} in (${ar})`
}
export function In(name, json, value) {
if (!json) return ''
var ar = cleanArray(
Object.keys(json).map(key => {
if (json[key] === undefined) return ''
return json[key][value] + ''
})
).join(',')
return ` ${name} in (${ar})`
}
/**
* 将一个普通的节点数组(带有指向父节点的指针)转换为嵌套的数据结构。
* @param {*} data 一组数据
* @param {*} option 包含以下字段的对象:
* parentProperty(String):可以找到父节点链接的属性的名称。默认值:'pid'。
* childrenProperty(String):将存储子节点的属性的名称。默认值:'children'。
* idProperty(String):唯一的节点标识符。默认值:'id'。
* nameProperty(String):节点的名称。默认值:'name'。
*/
export function FlatToNested(data, option) {
option = option || {}
var idProperty = option.idProperty || 'id'
var parentProperty = option.parentProperty || 'pid'
var childrenProperty = option.childrenProperty || 'children'
var res = []
var tmpMap = []
if (data != null) {
for (let i = 0; i < data.length; i++) {
tmpMap[data[i][idProperty]] = data[i]
if (tmpMap[data[i][parentProperty]] && data[i][idProperty] !== data[i][parentProperty]) {
if (!tmpMap[data[i][parentProperty]][childrenProperty]) {
tmpMap[data[i][parentProperty]][childrenProperty] = []
}
delete data[i][childrenProperty]
tmpMap[data[i][parentProperty]][childrenProperty].push(data[i])
} else {
res.push(data[i])
}
}
}
return res
}
/**
* 嵌套型格式转扁平型格式
* @param {Array} data 一组数据
*/
export function NestedToFlat(data, pid) {
var res = []
for (var i = 0; i < data.length; i++) {
res.push({
id: data[i].id,
name: data[i].name,
pid: pid || 0
})
if (data[i].children) {
res = res.concat(NestedToFlat(data[i].children, data[i].id))
}
}
return res
}
export function FlatToNestedRoutes(data) {
var idProperty = 'id'
var parentProperty = 'pid'
var childrenProperty = 'children'
var res = []
var tmpMap = []
for (let i = 0; i < data.length; i++) {
data[i] = TestDynamicRoutes(data[i])
tmpMap[data[i][idProperty]] = data[i]
if (tmpMap[data[i][parentProperty]] && data[i][idProperty] !== data[i][parentProperty]) {
if (!tmpMap[data[i][parentProperty]][childrenProperty]) {
tmpMap[data[i][parentProperty]][childrenProperty] = []
}
delete data[i].children
tmpMap[data[i][parentProperty]][childrenProperty].push(data[i])
} else {
delete data[i].id
delete data[i].pid
res.push(data[i])
}
}
return res
}
export function TestDynamicRoutes(menu) {
var route = {
path: null,
component: () => import(`@/views/${menu.Component}`),
redirect: null,
name: null,
meta: {
title: null,
icon: null
},
children: null,
id: 0,
pid: 0,
hidden: false
}
if (menu.Redirect != null) {
route['redirect'] = menu.Redirect
} else {
delete route.redirect
}
if (menu.Component == null) {
route['component'] = Layout
}
if (menu.Hidden === 'true') {
route['hidden'] = true
} else {
delete route.hidden
}
route['path'] = menu.Path
route['name'] = menu.Name
route['meta']['title'] = menu.Title
route['meta']['icon'] = menu.Icon
route['id'] = menu.Id
route['pid'] = menu.ParentId
return route
}
export function AddDynamicRoutes(menuList = [], routes = []) {
var temp = []
for (var i = 0; i < menuList.length; i++) {
if (menuList[i].Children && menuList[i].Children.length >= 1) {
temp = temp.concat(menuList[i].Children)
} else if (menuList[i].Hidden === 'false') { // 只显示非隐藏的菜单
// 创建路由配置
var route = {
path: menuList[i].Path,
component: null,
redirect: menuList[i].Redirect,
name: menuList[i].Name,
meta: {
title: menuList[i].Title,
icon: menuList[i].Icon
}
}
if (menuList[i].Component != null) {
route['component'] = () => import([menuList[i].Component])
}
routes.push(route)
}
}
if (temp.length >= 1) {
AddDynamicRoutes(temp, routes)
} else {
console.log('动态路由加载...')
console.log(routes)
console.log('动态路由加载完成.')
}
return routes
}
export function removeNull(option) {
if (!option) {
return
}
for (var attr in option) {
if (option[attr] === null) {
delete option[attr]
continue
}
if (typeof option[attr] === 'object') {
removeNull(option[attr])
}
}
}
export function formatterMoney(intInput) {
// 将输入参数转换为字符串形式
var strInput = Math.abs(intInput).toString();
//如果有小数,把小数部分提取出来
var strXS = "";
if (strInput.indexOf(".", 0) != -1) {
strXS = strInput.substring(strInput.split(".")[0].length, strInput.length);
strInput = strInput.split(".")[0];
}
//获取输入参数的长度
var iLen = strInput.length;
//如果输入参数的长度小于等于3,则直接返回
//否则,再进行处理
if (iLen <= 3) {
return intInput;
} else {
//首先取模,以作为起始点,每3位截取一次存入数组,最后再进行拼接返回
var iMod = iLen % 3;
//每3位截取的起始点
var iStart = iMod;
//每3位截取的存储数组
var aryReturn = [];
//循环处理:每3位截取一次 存储到数组
while (iStart + 3 <= iLen) {
aryReturn[aryReturn.length] = strInput.substring(iStart, iStart + 3);
iStart = iStart + 3;
}
//将数组中的数据连接起来
aryReturn = aryReturn.join(",");
//处理输入参数长度不是3的倍数的情况
if (iMod != 0) {
aryReturn = strInput.substring(0, iMod) + "," + aryReturn;
}
//处理负数的情况
if (intInput < 0) {
aryReturn = "-" + aryReturn;
}
return aryReturn + strXS;
}
}