ruoyi-vue-plus-前端工具篇
# 前端工具篇
以下工具写法会采用 ts标识类型 以便区分传参应用方式
# auth
token管理
返回 | 方法 | 说明 |
---|---|---|
void | setToken(token: string) | 修改token |
string | getToken() | 获取token |
void | removeToken() | 移除token |
# erroeCode
异常码对象 , 略..
export default {
'401': '认证失败,无法访问系统资源',
'403': '当前操作没有权限',
'404': '访问资源不存在',
'default': '系统未知错误,请反馈给管理员'
}
# index
封装常用工具
返回 | 方法 | 说明 |
---|---|---|
stirng | formatDate(cellValue: string | number) | 时间格式化 , Date构建格式支持即可 |
string | formatTime(time: number, option: string) | 最近时间格式化 time: 仅支持时间戳 ; option: 格式模板 |
object | getQueryObject(url: string) | 获取 链接请求参数 (不传参获取当前url) |
nubmer | byteLength(str: string) | 获取 参数的字节长度 |
array | cleanArray(actual: array) | 清除 数组空元素 |
string | param(json: object) | obj转化为 url传参形式 |
object | param2Obj(url: string) | url转化为 请求参数对象 |
string | html2Text(val: string) | 提取html中的内容 |
object | objectMerge(target: object, source: object) | 对象合并 |
void | toggleClass(element: HTMLElement, className: string) | h5标签class样式切换 (添加&删除) |
Date | getTime(type: string) | 获取指定类型时间 (无参获取当前时间) |
function | debounce(func, wait: number, immediate: boolean) | 防抖 (使用方式如下) 31:35 |
array | object | deepClone(source: object) | 深度克隆 |
array | uniqueArr(arr: array) | 数组去重 |
string | createUniqueString() | 创建不重复的字符串数组 |
boolean | hasClass(ele, cls: string) | 判断 class样式是否存在 , 目标h5标签 |
void | addClass(ele, cls: string) | 添加 class样式 , 目标 h5标签 |
void | removeClass(ele, cls: string) | 移除 class样式 , 目标 h5标签 |
string | titleCase(str: string) | 首字母大写 |
string | camelCase(str: string) | 下划线转驼峰 |
string | isNumberStr(str: string) | 判断数值字符串 |
# 源码
点击展开
import { parseTime } from './ruoyi'
/**
* 表格时间格式化
*/
export function formatDate(cellValue) {
if (cellValue == null || cellValue == "") return "";
var date = new Date(cellValue)
var year = date.getFullYear()
var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}
/**
* @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 = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
if (!search) {
return {}
}
const obj = {}
const searchArr = search.split('&')
searchArr.forEach(v => {
const index = v.indexOf('=')
if (index !== -1) {
const name = v.substring(0, index)
const val = v.substring(index + 1, v.length)
obj[name] = val
}
})
return obj
}
/**
* @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
}
/**
* @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 function makeMap(str, expectsLowerCase) {
const map = Object.create(null)
const list = str.split(',')
for (let i = 0; i < list.length; i++) {
map[list[i]] = true
}
return expectsLowerCase
? val => map[val.toLowerCase()]
: val => map[val]
}
export const exportDefault = 'export default '
export const beautifierConf = {
html: {
indent_size: '2',
indent_char: ' ',
max_preserve_newlines: '-1',
preserve_newlines: false,
keep_array_indentation: false,
break_chained_methods: false,
indent_scripts: 'separate',
brace_style: 'end-expand',
space_before_conditional: true,
unescape_strings: false,
jslint_happy: false,
end_with_newline: true,
wrap_line_length: '110',
indent_inner_html: true,
comma_first: false,
e4x: true,
indent_empty_lines: true
},
js: {
indent_size: '2',
indent_char: ' ',
max_preserve_newlines: '-1',
preserve_newlines: false,
keep_array_indentation: false,
break_chained_methods: false,
indent_scripts: 'normal',
brace_style: 'end-expand',
space_before_conditional: true,
unescape_strings: false,
jslint_happy: true,
end_with_newline: true,
wrap_line_length: '110',
indent_inner_html: true,
comma_first: false,
e4x: true,
indent_empty_lines: true
}
}
// 首字母大小
export function titleCase(str) {
return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}
// 下划转驼峰
export function camelCase(str) {
return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase())
}
export function isNumberStr(str) {
return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
}
# 应用
点击展开
<template>
<div>
<el-button @click="debounceLoad">防抖(延迟执行)</el-button>
<el-button @click="debounceLoadWithTrue">防抖(快速执行)</el-button>
<el-button @click="debounceLoadError">防抖(错误示范)</el-button>
</div>
</template>
<script>
import {
cleanArray,
debounce, deepClone,
formatDate,
formatTime,
getQueryObject,
html2Text,
objectMerge,
param,
param2Obj
} from "@/utils";
export default {
name: "Index",
data() {
return {
};
},
mounted() {
// this.deepCloneLoad()
// this.objectMergeLoad()
// this.html2TextLoad()
// this.param2ObjLoad()
// this.paramLoad()
// this.cleanArrayLoad()
// this.formatTimeLoad()
// this.getQueryObjectLoad()
// this.formatDateLoad()
},
methods: {
deepCloneLoad() {
const target = {zs: 1, age: 22}
const obj = deepClone(target)
console.log(target === obj) // false
},
// 方法单独调用不能视为同一内存地址控制
debounceLoad: debounce(() => {
console.log("延迟执行")
}, 2000, false),
debounceLoadWithTrue: debounce(() => {
console.log("快速执行")
}, 2000, true),
// 错误用法 (每次点击控制的是不同地址的防抖对象)
debounceLoadError() {
const fun = debounce(() => {
console.log("快速执行(错误)")
}, 1000, true)
fun()
},
objectMergeLoad() {
const obj = objectMerge({a: 1}, {b: 2})
console.log(obj) // {a: 1, b: 2}
const obj2 = objectMerge({a: 1,c: 999}, {b: 2, c: 3})
console.log(obj2) // {a: 1, c: 3, b: 2}
},
html2TextLoad() {
const data = html2Text("<p><a href='http://www.bozhu12.cc'>柏竹博客</a></p>");
console.log(data) // 柏竹博客
},
param2ObjLoad() {
const data = param2Obj("http://localhost/index?name=zs&age=22")
console.log(data) // {name: 'zs', age: '22'}
},
paramLoad() {
const par = param({name: 'zs', age: 22})
console.log(par) // name=zs&age=22
},
cleanArrayLoad() {
const arr = cleanArray([1,'2',null,'',9,{},undefined,10,0,]);
console.log(arr) // [1, '2', 9, {}, 10]
},
formatTimeLoad() {
const date = formatTime("2024-06-12T23:23:00")
console.log(date) // NaN月NaN日NaN时NaN分
const date2 = formatTime("2024-06-12T23:23:00", "yyyy-MM-dd hh:mm:ss")
console.log(date2) // null
const date3 = formatTime(new Date().getTime())
console.log(date3) // 刚刚
// 一天时差
const date4 = formatTime(new Date().getTime() - 90000000, "yyyy-MM-dd hh:mm:ss")
console.log(date4) // 1天前
},
getQueryObjectLoad() {
// http://localhost/index?name=zs&age=22
const query = getQueryObject();
console.log(query) // {name: 'zs', age: '22'}
const query2 = getQueryObject("http://localhost/index?name=lz&age=32");
console.log(query2) // {name: 'lz', age: '32'}
},
formatDateLoad() {
// 日期字符串 & 时间戳
const date = formatDate("2024-06-12T23:23:00")
console.log(date) // 2024-06-12 23:23:00
const date2 = formatDate(new Date().getTime())
console.log(date2) // 2024-06-16 20:12:26
},
},
};
</script>
<style scoped lang="scss">
</style>
# jsencrypt
加解密工具
返回 | 方法 | 说明 |
---|---|---|
string | encrypt(string: txt) | 加密 |
string | decrypt(string: txt) | 解密 |
# 源码
点击展开
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'
// 密钥对生成 http://web.chacuo.net/netrsakeypair
const publicKey = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdH\n' +
'nzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ=='
// 生成的
const privateKey = 'MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAqhHyZfSsYourNxaY\n' +
'7Nt+PrgrxkiA50efORdI5U5lsW79MmFnusUA355oaSXcLhu5xxB38SMSyP2KvuKN\n' +
'PuH3owIDAQABAkAfoiLyL+Z4lf4Myxk6xUDgLaWGximj20CUf+5BKKnlrK+Ed8gA\n' +
'kM0HqoTt2UZwA5E2MzS4EI2gjfQhz5X28uqxAiEA3wNFxfrCZlSZHb0gn2zDpWow\n' +
'cSxQAgiCstxGUoOqlW8CIQDDOerGKH5OmCJ4Z21v+F25WaHYPxCFMvwxpcw99Ecv\n' +
'DQIgIdhDTIqD2jfYjPTY8Jj3EDGPbH2HHuffvflECt3Ek60CIQCFRlCkHpi7hthh\n' +
'YhovyloRYsM+IS9h/0BzlEAuO0ktMQIgSPT3aFAgJYwKpqRYKlLDVcflZFCKY7u3\n' +
'UP8iWi1Qw0Y='
// 加密
export function encrypt(txt) {
const encryptor = new JSEncrypt()
encryptor.setPublicKey(publicKey) // 设置公钥
return encryptor.encrypt(txt) // 对数据进行加密
}
// 解密
export function decrypt(txt) {
const encryptor = new JSEncrypt()
encryptor.setPrivateKey(privateKey) // 设置私钥
return encryptor.decrypt(txt) // 对数据进行解密
}
# permission
权限校验工具
用户登录后会缓存身份的权限标识以及身份信息
返回 | 方法 | 说明 |
---|---|---|
boolean | checkPermi(any[]: value) | 权限标识校验 |
boolean | checkRole(string: value) | 身份校验 |
# 源码
点击展开
import store from '@/store'
/**
* 字符权限校验
* @param {Array} value 校验值
* @returns {Boolean}
*/
export function checkPermi(value) {
if (value && value instanceof Array && value.length > 0) {
const permissions = store.getters && store.getters.permissions
const permissionDatas = value
const all_permission = "*:*:*";
const hasPermission = permissions.some(permission => {
return all_permission === permission || permissionDatas.includes(permission)
})
if (!hasPermission) {
return false
}
return true
} else {
console.error(`need roles! Like checkPermi="['system:user:add','system:user:edit']"`)
return false
}
}
/**
* 角色权限校验
* @param {Array} value 校验值
* @returns {Boolean}
*/
export function checkRole(value) {
if (value && value instanceof Array && value.length > 0) {
const roles = store.getters && store.getters.roles
const permissionRoles = value
const super_admin = "admin";
const hasRole = roles.some(role => {
return super_admin === role || permissionRoles.includes(role)
})
if (!hasRole) {
return false
}
return true
} else {
console.error(`need roles! Like checkRole="['admin','editor']"`)
return false
}
}
# ruoyi
ruoyi通用方法
返回 | 方法 | 说明 |
---|---|---|
string | parseTime(string | object | number: time, string: pattern) | 格式化日期 |
void | resetForm(Element: refName) | 表单重置 |
object | addDateRange(object: params, any[]: dateRange, string: propName) | 添加日期范围 |
string | sprintf(string: str) | 字符串格式化 |
any | parseStrEmpty(any: str) | 转换字符串 , 其他类型转化本身 |
object | mergeRecursive(object: source, object: target) | 数据合并 |
object | handleTree(object: data, string: id, string: parenId, string: children) | 构造树型结构数据 (不支持大量数据) |
string | tansParams(object: params) | 参数处理 , url应用的参数 |
boolean | blobValidate(string: data) | 验证是否blob格式 |
# 源码
点击展开
// 日期格式化
export function parseTime(time, pattern) {
if (arguments.length === 0 || !time) {
return null
}
const format = pattern || '{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)
} else if (typeof time === 'string') {
time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
}
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
}
// 表单重置
export function resetForm(refName) {
if (this.$refs[refName]) {
this.$refs[refName].resetFields();
}
}
// 添加日期范围
export function addDateRange(params, dateRange, propName) {
let search = params;
search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
dateRange = Array.isArray(dateRange) ? dateRange : [];
if (typeof (propName) === 'undefined') {
search.params['beginTime'] = dateRange[0];
search.params['endTime'] = dateRange[1];
} else {
search.params['begin' + propName] = dateRange[0];
search.params['end' + propName] = dateRange[1];
}
return search;
}
// 回显数据字典
export function selectDictLabel(datas, value) {
if (value === undefined) {
return "";
}
var actions = [];
Object.keys(datas).some((key) => {
if (datas[key].value == ('' + value)) {
actions.push(datas[key].label);
return true;
}
})
if (actions.length === 0) {
actions.push(value);
}
return actions.join('');
}
// 回显数据字典(字符串、数组)
export function selectDictLabels(datas, value, separator) {
if (value === undefined || value.length ===0) {
return "";
}
if (Array.isArray(value)) {
value = value.join(",");
}
var actions = [];
var currentSeparator = undefined === separator ? "," : separator;
var temp = value.split(currentSeparator);
Object.keys(value.split(currentSeparator)).some((val) => {
var match = false;
Object.keys(datas).some((key) => {
if (datas[key].value == ('' + temp[val])) {
actions.push(datas[key].label + currentSeparator);
match = true;
}
})
if (!match) {
actions.push(temp[val] + currentSeparator);
}
})
return actions.join('').substring(0, actions.join('').length - 1);
}
// 字符串格式化(%s )
export function sprintf(str) {
var args = arguments, flag = true, i = 1;
str = str.replace(/%s/g, function () {
var arg = args[i++];
if (typeof arg === 'undefined') {
flag = false;
return '';
}
return arg;
});
return flag ? str : '';
}
// 转换字符串,undefined,null等转化为""
export function parseStrEmpty(str) {
if (!str || str == "undefined" || str == "null") {
return "";
}
return str;
}
// 数据合并
export function mergeRecursive(source, target) {
for (var p in target) {
try {
if (target[p].constructor == Object) {
source[p] = mergeRecursive(source[p], target[p]);
} else {
source[p] = target[p];
}
} catch (e) {
source[p] = target[p];
}
}
return source;
};
/**
* 构造树型结构数据
* @param {*} data 数据源
* @param {*} id id字段 默认 'id'
* @param {*} parentId 父节点字段 默认 'parentId'
* @param {*} children 孩子节点字段 默认 'children'
*/
export function handleTree(data, id, parentId, children) {
let config = {
id: id || 'id',
parentId: parentId || 'parentId',
childrenList: children || 'children'
};
var childrenListMap = {};
var nodeIds = {};
var tree = [];
for (let d of data) {
let parentId = d[config.parentId];
if (childrenListMap[parentId] == null) {
childrenListMap[parentId] = [];
}
nodeIds[d[config.id]] = d;
childrenListMap[parentId].push(d);
}
for (let d of data) {
let parentId = d[config.parentId];
if (nodeIds[parentId] == null) {
tree.push(d);
}
}
for (let t of tree) {
adaptToChildrenList(t);
}
function adaptToChildrenList(o) {
if (childrenListMap[o[config.id]] !== null) {
o[config.childrenList] = childrenListMap[o[config.id]];
}
if (o[config.childrenList]) {
for (let c of o[config.childrenList]) {
adaptToChildrenList(c);
}
}
}
return tree;
}
/**
* 参数处理
* @param {*} params 参数
*/
export function tansParams(params) {
let result = ''
for (const propName of Object.keys(params)) {
const value = params[propName];
var part = encodeURIComponent(propName) + "=";
if (value !== null && value !== "" && typeof (value) !== "undefined") {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
let params = propName + '[' + key + ']';
var subPart = encodeURIComponent(params) + "=";
result += subPart + encodeURIComponent(value[key]) + "&";
}
}
} else {
result += part + encodeURIComponent(value) + "&";
}
}
}
return result
}
// 验证是否为blob格式
export function blobValidate(data) {
return data.type !== 'application/json'
}
# 应用
点击展开
<template>
<div>
<el-form ref="elForm" :model="formData" size="medium" label-width="100px">
<el-form-item label="单行文本" prop="field101">
<el-input v-model="fromText" placeholder="请输入单行文本" clearable :style="{width: '100%'}"/>
</el-form-item>
<el-form-item size="large">
<el-button @click="resetFormLoad">重置</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
import {
cleanArray,
debounce, deepClone,
formatDate,
formatTime,
getQueryObject,
html2Text,
objectMerge,
param,
param2Obj
} from "@/utils";
import {
addDateRange,
handleTree,
mergeRecursive,
parseStrEmpty,
parseTime,
resetForm,
sprintf,
tansParams
} from "@/utils/ruoyi";
export default {
name: "Index",
data() {
return {
fromText: '',
formData: {},
};
},
mounted() {
// this.parseTimeLoad()
// this.addDateRangeLoad()
// this.sprintfLoad()
// this.parseStrEmptyLoad()
// this.mergeRecursiveLoad()
this.tansParamsLoad()
},
methods: {
parseTimeLoad() {
console.log(parseTime(new Date())); // 2024-07-02 20:43:28
// 一天时差
console.log(parseTime(new Date().getTime() - 90000000)); // 2024-07-01 19:43:28
},
resetFormLoad() {
resetForm('elForm')
},
// 封装时间范围使用
addDateRangeLoad() {
const arrTime = [new Date(2016, 9, 10, 0, 0, 0), new Date(2016, 10, 10, 23, 59, 59)]
console.log(addDateRange(this.formData, arrTime).params)
// {beginTime: Mon Oct 10 2016 00:00:00 GMT+0800 (台北标准时间), endTime: Thu Nov 10 2016 23:59:59 GMT+0800 (台北标准时间)}
console.log(addDateRange(this.formData, arrTime, "bozhu").params)
// {beginTime: Mon Oct 10 2016 00:00:00 GMT+0800 (台北标准时间), endTime: Thu Nov 10 2016 23:59:59 GMT+0800 (台北标准时间), beginbozhu: Mon Oct 10 2016 00:00:00 GMT+0800 (台北标准时间), endbozhu: Thu Nov 10 2016 23:59:59 GMT+0800 (台北标准时间)}
},
sprintfLoad() {
console.log(sprintf("hello %s %s", "bozhu", "!")) // hello bozhu !
},
parseStrEmptyLoad() {
console.log(parseStrEmpty(null)) // ""
console.log(parseStrEmpty(undefined)) // ""
parseStrEmpty("") // ""
console.log(parseStrEmpty("123")) // 123
},
mergeRecursiveLoad() {
const target = {
a: 1,
b: 2,
c: {
d: 3,
e: 4,
},
f: [2, 3, 4],
};
const obj = mergeRecursive(target, {
b: 3,
c: {
e: 5,
f: 6,
},
g: [1, 2, 3],
});
console.log(obj) // {a: 1, b: 3, c: {d: 3, e: 5, f: 6}, f: [1, 2, 3], g: [1, 2, 3]
},
tansParamsLoad() {
console.log(tansParams({name: 'lz', age: 22})) // name=lz&age=22&
}
},
};
</script>
# validate
校验数据工具
返回 | 方法 | 说明 |
---|---|---|
boolean | isExternal(string: path) | 是否外部链接 |
boolean | validUsername(string: str) | 校验有效用户名 |
boolean | validURL(string: url) | 校验有效url |
boolean | validLowerCase(string: email) | 校验有效小写 |
boolean | validUpperCase(string: str) | 校验有效大写 |
boolean | validAlphabets(string: str) | 校验字母 |
boolean | validEmail(string: email) | 校验邮箱 |
boolean | isString(string: str) | 校验字符串 |
boolean | isArray(arg: array) | 校验数组 |
# 源码
点击展开
/**
* @param {string} path
* @returns {Boolean}
*/
export function isExternal(path) {
return /^(https?:|mailto:|tel:)/.test(path)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validUsername(str) {
const valid_map = ['admin', 'editor']
return valid_map.indexOf(str.trim()) >= 0
}
/**
* @param {string} url
* @returns {Boolean}
*/
export function validURL(url) {
const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
return reg.test(url)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validLowerCase(str) {
const reg = /^[a-z]+$/
return reg.test(str)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validUpperCase(str) {
const reg = /^[A-Z]+$/
return reg.test(str)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validAlphabets(str) {
const reg = /^[A-Za-z]+$/
return reg.test(str)
}
/**
* @param {string} email
* @returns {Boolean}
*/
export function validEmail(email) {
const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return reg.test(email)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function isString(str) {
if (typeof str === 'string' || str instanceof String) {
return true
}
return false
}
/**
* @param {Array} arg
* @returns {Boolean}
*/
export function isArray(arg) {
if (typeof Array.isArray === 'undefined') {
return Object.prototype.toString.call(arg) === '[object Array]'
}
return Array.isArray(arg)
}
# 应用
点击展开
console.log("isExternal", isExternal("https://www.baidu.com")) // isExternal true
console.log("validUsername", validUsername("12312kjskl")) // validUsername false
console.log("validURL", validURL("https://www.baidu.com")) // validURL true
console.log("validLowerCase", validLowerCase("ksldjf")) // validLowerCase true
console.log("validLowerCase", validLowerCase("KSLDJF")) // validLowerCase false
console.log("validUpperCase", validUpperCase("ABC")) // validUpperCase true
console.log("validUpperCase", validUpperCase("abc")) // validUpperCase false
console.log("validUsername", validUsername("12312kjskl")) // validUsername false
console.log("validUsername", validUsername("12312kjskl")) // validUsername false
console.log("validAlphabets", validAlphabets("123@qq.com")) // validAlphabets false
console.log("validAlphabets", validAlphabets("abc")) // validAlphabets true
console.log("validEmail", validEmail("123@qq.com")) // validEmail true