feat: 初始化版本!

This commit is contained in:
tianyongbao
2024-05-31 13:08:46 +08:00
parent 884a84802d
commit b3fe699735
587 changed files with 103758 additions and 27 deletions

13
src/utils/auth.ts Normal file
View File

@@ -0,0 +1,13 @@
const TokenKey = 'App-Token'
export function getToken():string {
return uni.getStorageSync(TokenKey)
}
export function setToken(token:string) {
return uni.setStorageSync(TokenKey, token)
}
export function removeToken() {
return uni.removeStorageSync(TokenKey)
}

54
src/utils/common.ts Normal file
View File

@@ -0,0 +1,54 @@
/**
* 显示消息提示框
* @param content 提示的标题
*/
export function toast(content:string) {
uni.showToast({
icon: 'none',
title: content
})
}
/**
* 显示模态弹窗
* @param content 提示的标题
*/
export function showConfirm(content:string):Promise<any> {
return new Promise((resolve, reject) => {
uni.showModal({
title: '提示',
content: content,
cancelText: '取消',
confirmText: '确定',
success: function(res) {
resolve(res)
}
})
})
}
/**
* 参数处理
* @param params 参数
*/
export function tansParams(params:any) {
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
}

8
src/utils/constant.ts Normal file
View File

@@ -0,0 +1,8 @@
const constant = {
avatar: 'vuex_avatar',
name: 'vuex_name',
roles: 'vuex_roles',
permissions: 'vuex_permissions'
}
export default constant

30
src/utils/dict.ts Normal file
View File

@@ -0,0 +1,30 @@
import useDictStore from "@/store/modules/dict";
import { getDicts } from "@/api/system/dict/data";
import { Ref, ref, toRefs } from "vue";
/**
* 获取字典数据
*/
export function useDict(...args: any[]) {
const res: Ref<any> = ref({});
return (() => {
args.forEach((dictType, index) => {
res.value[dictType] = [];
const dicts = useDictStore().getDict(dictType);
if (dicts) {
res.value[dictType] = dicts;
} else {
getDicts(dictType).then((resp) => {
res.value[dictType] = resp.data.map((p: any) => ({
label: p.dictLabel,
value: p.dictValue,
elTagType: p.listClass,
elTagClass: p.cssClass,
}));
useDictStore().setDict(dictType, res.value[dictType]);
});
}
});
return toRefs(res.value);
})();
}

6
src/utils/errorCode.ts Normal file
View File

@@ -0,0 +1,6 @@
export default {
'401': '认证失败,无法访问系统资源',
'403': '当前操作没有权限',
'404': '访问资源不存在',
'default': '系统未知错误,请反馈给管理员'
}

131
src/utils/geek.ts Normal file
View File

@@ -0,0 +1,131 @@
import { tansParams } from "./ruoyi";
/**
* 通配符比较
* @param {*} str 待比较的字符串
* @param {*} pattern 含有*或者?通配符的字符串
* @returns
*/
export function wildcardCompare(str: string, pattern: string): boolean {
const regex = pattern.replace(/[*?]/g, (match) => {
if (match === "*") {
return ".*";
} else if (match === "?") {
return ".";
} else {
return match;
}
});
const regexPattern = new RegExp("^" + regex + "$");
return regexPattern.test(str);
}
/**
* 深度复制
* @param obj 待复制的对象
* @returns 复制的对象
*/
export function deepClone(obj: any) {
if (obj == null || typeof obj !== "object") {
return obj;
}
let result;
if (Array.isArray(obj)) {
result = [];
} else {
result = new Map();
}
for (let [key, value] of Object.entries(obj)) {
// @ts-ignore
result[key] = deepClone(value);
}
return result;
}
/**
* 深度复制
* @param obj 待复制的对象
* @param result 要复制到的对象
* @returns 复制的对象
*/
export function deepCloneTo<T>(obj: T, result: T) {
if (obj == null || typeof obj !== "object") {
return obj;
}
for (let [key, value] of Object.entries(obj)) {
// @ts-ignore
result[key] = deepClone(value);
}
return result;
}
/**
* 获取uuid
* @returns 生成的uuid字符串
*/
export function generateUUID(): string {
let uuid = "";
const chars = "0123456789abcdef";
for (let i = 0; i < 32; i++) {
if (i === 8 || i === 12 || i === 16 || i === 20) {
uuid += "-";
}
uuid += chars[Math.floor(Math.random() * chars.length)];
}
return uuid;
}
/**
* 获取code
* @returns 生成的code字符串
*/
export async function getWxCode(appid?: string,redirect_uri?:string) {
// #ifdef H5
if (appid == undefined || redirect_uri == undefined) return ""
let code = "";
// 截取url中的code方法
function getUrlCode() {
let url = location.search;
console.log(url);
let theRequest: any = new Object();
if (url.indexOf("?") != -1) {
let str = url.substr(1);
let strs = str.split("&");
for (let i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
}
}
return theRequest as { code: string };
}
code = getUrlCode().code; // 截取code
if (code == undefined || code == "" || code == null) {
// 如果没有code则去请求
console.log("h5");
let href= "https://open.weixin.qq.com/connect/oauth2/authorize?"+
tansParams({
appid: appid,
redirect_uri: redirect_uri,
response_type: "code",
scope: "snsapi_userinfo",
state: "STATE",
}) +
"#wechat_redirect";
console.log(href);
setTimeout(() => {
window.location.href = href;
}, 5000);
} else {
return code;
}
// #endif
// #ifdef MP-WEIXIN
// @ts-ignore
const res = await wx.login();
return res.code;
// #endif
}

51
src/utils/permission.ts Normal file
View File

@@ -0,0 +1,51 @@
import useUserStore from '@/store/modules/user'
/**
* 字符权限校验
* @param {Array} value 校验值
* @returns {Boolean}
*/
export function checkPermi(value:Array<string>) {
if (value && value instanceof Array && value.length > 0) {
const permissions:Array<string> = useUserStore().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:Array<string>) {
if (value && value instanceof Array && value.length > 0) {
const roles:Array<string> = useUserStore().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
}
}

90
src/utils/request.ts Normal file
View File

@@ -0,0 +1,90 @@
import config from '@/config'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast, showConfirm, tansParams } from '@/utils/common'
import { RequestConfig, ResponseData } from '@/types/request'
import useUserStore from '@/store/modules/user'
let timeout = 10000
const baseUrl = config.baseUrl
const request = <T>(config: RequestConfig): Promise<ResponseData<T>> => {
// 是否需要设置 token
const isToken = (config.headers || {}).isToken === false
config.header = config.header || {}
if (getToken() && !isToken) {
config.header['Authorization'] = 'Bearer ' + getToken()
}
// get请求映射params参数
if (config.params) {
let url = config.url + '?' + tansParams(config.params)
url = url.slice(0, -1)
config.url = url
}
return new Promise((resolve, reject) => {
uni.request({
method: config.method || 'GET',
timeout: config.timeout || timeout,
url: (config.baseUrl || baseUrl) + config.url,
data: config.data,
header: config.header,
dataType: 'json'
}).then(response => {
/* let [error, res] = response
if (error) {
toast('后端接口连接异常')
reject('后端接口连接异常')
return
} */
const res = response
const data: ResponseData<T> = res.data as ResponseData<T>
const code = data.code || 200
// @ts-ignore
const msg: string = errorCode[code] || data.msg || errorCode['default']
if (code === 401) {
showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
if (res.confirm) {
useUserStore().logOut().then(res => {
uni.reLaunch({ url: '/pages/login' })
})
}
})
reject('无效的会话,或者会话已过期,请重新登录。')
} else if (code === 500) {
toast(msg)
reject('500')
} else if (code !== 200) {
toast(msg)
reject(code)
}
resolve(data)
})
.catch(error => {
let { message } = error
if (message === 'Network Error') {
message = '后端接口连接异常'
} else if (message.includes('timeout')) {
message = '系统接口请求超时'
} else if (message.includes('Request failed with status code')) {
message = '系统接口' + message.substr(message.length - 3) + '异常'
}
toast(message)
reject(error)
})
})
}
export function postAction(url: string, data?: any, isToken: boolean = true) {
return request({ data, url, method: 'POST', headers: { isToken }, })
}
export function getAction(url: string, params?: any, isToken: boolean = true) {
return request({ params, url, method: 'GET', headers: { isToken }, })
}
export function putAction(url: string, data?: any, isToken: boolean = true) {
return request({ data, url, method: 'PUT', headers: { isToken }, })
}
export function deleteAction(url: string, data?: any, isToken: boolean = true) {
return request({ data, url, method: 'DELETE', headers: { isToken }, })
}
export default request

226
src/utils/ruoyi.js Normal file
View File

@@ -0,0 +1,226 @@
/**
* 通用js方法封装处理
* Copyright (c) 2019 ruoyi
*/
// 日期格式化
/**
*
* @param {*} time 时间(Date对象、时间戳、时间字符串)
* @param {*} pattern 格式模板 默认'{y}-{m}-{d} {h}:{i}:{s}' y:年 m:月 d:日 h:时 i:分 s:秒 a:星期
* @returns 按照模板格式的时间字符串
*/
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) {
var actions = [];
Object.keys(datas).some((key) => {
if (datas[key].value == ('' + value)) {
actions.push(datas[key].label);
return true;
}
})
return actions.join('');
}
// 回显数据字典(字符串数组)
export function selectDictLabels(datas, value, separator) {
var actions = [];
var currentSeparator = undefined === separator ? "," : separator;
var temp = value.split(currentSeparator);
Object.keys(value.split(currentSeparator)).some((val) => {
Object.keys(datas).some((key) => {
if (datas[key].value == ('' + temp[val])) {
actions.push(datas[key].label + 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 praseStrEmpty(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 && typeof (value) !== "undefined") {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
if (value[key] !== null && 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 async function blobValidate(data) {
try {
const text = await data.text();
JSON.parse(text);
return false;
} catch (error) {
return true;
}
}

33
src/utils/storage.ts Normal file
View File

@@ -0,0 +1,33 @@
import constant from './constant'
// 存储变量名
let storageKey = 'storage_data'
// 存储节点变量名
let storageNodeKeys = [constant.avatar, constant.name, constant.roles, constant.permissions]
// 存储的数据
let storageData = uni.getStorageSync(storageKey) || {}
const storage = {
set: function(key:string, value:any) {
if (storageNodeKeys.indexOf(key) != -1) {
let tmp = uni.getStorageSync(storageKey)
tmp = tmp ? tmp : {}
tmp[key] = value
uni.setStorageSync(storageKey, tmp)
}
},
get: function(key:string) {
return storageData[key] || ""
},
remove: function(key:string) {
delete storageData[key]
uni.setStorageSync(storageKey, storageData)
},
clean: function() {
uni.removeStorageSync(storageKey)
}
}
export default storage

73
src/utils/upload.ts Normal file
View File

@@ -0,0 +1,73 @@
import config from '@/config'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast, showConfirm, tansParams } from '@/utils/common'
import { ResponseData, RequestUploadConfig } from '@/types/request'
import useUserStore from '@/store/modules/user'
let timeout = 10000
const baseUrl = config.baseUrl
const upload = <T>(config: RequestUploadConfig): Promise<ResponseData<T>> => {
// 是否需要设置 token
const isToken = (config.headers || {}).isToken === false
config.header = config.header || {}
if (getToken() && !isToken) {
config.header['Authorization'] = 'Bearer ' + getToken()
}
// get请求映射params参数
if (config.params) {
let url = config.url + '?' + tansParams(config.params)
url = url.slice(0, -1)
config.url = url
}
const userStore = useUserStore()
return new Promise((resolve, reject) => {
uni.uploadFile({
timeout: config.timeout || timeout,
url: baseUrl + config.url,
filePath: config.filePath,
name: config.name || 'file',
header: config.header,
formData: config.formData,
success: (res) => {
let result = JSON.parse(res.data)
const code = result.code || 200
// @ts-ignore
const msg = errorCode[code] || result.msg || errorCode['default']
if (code === 200) {
resolve(result)
} else if (code == 401) {
showConfirm("登录状态已过期,您可以继续留在该页面,或者重新登录?").then(res => {
if (res.confirm) {
userStore.logOut().then(res => {
uni.reLaunch({ url: '/pages/login' })
})
}
})
reject('无效的会话,或者会话已过期,请重新登录。')
} else if (code === 500) {
toast(msg)
reject('500')
} else if (code !== 200) {
toast(msg)
reject(code)
}
},
fail: (error: any) => {
let { message } = error
if (message == 'Network Error') {
message = '后端接口连接异常'
} else if (message.includes('timeout')) {
message = '系统接口请求超时'
} else if (message.includes('Request failed with status code')) {
message = '系统接口' + message.substr(message.length - 3) + '异常'
}
toast(message)
reject(error)
}
})
})
}
export default upload