2022年5月29日从svn移到git

This commit is contained in:
daihh
2022-05-29 18:56:34 +08:00
commit b050613020
488 changed files with 68444 additions and 0 deletions

10
src/utils/constants.js Normal file
View File

@@ -0,0 +1,10 @@
/**页面设置的一些常量*/
const constants={
Cookies:{
name:'login_name',
password:'login_password',
rememberMe:'login_rememberMe',
}
}
export default constants

107
src/utils/datetime.js Normal file
View File

@@ -0,0 +1,107 @@
// export function formatsec (date, fmt) {
// if (/(y+)/.test(fmt)) {
// fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
// }
// let o = {
// 'M+': new date(date).getMonth() +1,
// 'd+': date.getDate(),
// 'h+': date.getHours(),
// 'm+': date.getMinutes(),
// 's+': date.getSeconds()
// };
// for (let k in o) {
// if (new RegExp(`(${k})`).test(fmt)) {
// let str = o[k] + '';
// fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
// }
// }
// return fmt;
// };
// function padLeftZero (str) {
// return ('00' + str).substr(str.length);
// }
export function formatsec(date){
var year = new Date(date).getFullYear(),
month = new Date(date).getMonth() + 1,//月份是从0开始的
day = new Date(date).getDate(),
hour = new Date(date).getHours(),
min = new Date(date).getMinutes(),
sec = new Date(date).getSeconds();
if(month<10){month='0'+month}
if(day<10){day='0'+day}
if(hour<10){hour='0'+hour}
if(min<10){min='0'+min}
if(sec<10){sec='0'+sec}
var newTime = year + '-' +
month + '-' +
day + ' ' +
hour + ':' +
min + ':' +
sec;
return newTime;
}
export function formatDate(date){
var year = date.getFullYear(),
month = date.getMonth() + 1,//月份是从0开始的
day = date.getDate(),
hour = date.getHours(),
min = date.getMinutes(),
sec = date.getSeconds();
if(month<10){month='0'+month}
if(day<10){day='0'+day}
if(hour<10){hour='0'+hour}
if(min<10){min='0'+min}
if(sec<10){sec='0'+sec}
var newTime = year + '-' +
month + '-' +
day + ' ' +
hour + ':' +
min + ':' +
sec;
return newTime;
}
// 秒转时分秒
export function formatSeconds(value) {
let result = parseInt(value)
let h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
let m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
let s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));
let res = '';
if(h !== '00'){
res += `${h}小时`;
}
if(m !== '00' || h !== '00'){
res += `${m}`;
}
res += `${s}`;
return res;
}
// 秒转时分秒
export function formatSecondsToHours(value) {
let result = parseInt(value)
let h = Math.floor(result / 3600);
let m = Math.floor((result / 60 % 60));
let s = Math.floor((result % 60));
let res = '';
if(h>0){
res += `${h}小时`;
}else{
if(m>0){
let mm=Math.floor(m /60);
res += `${mm}小时`;
}else{
res += '0小时';
}
}
return res;
}

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

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

458
src/utils/index.js Normal file
View File

@@ -0,0 +1,458 @@
let parseTime = function(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), '/');
}
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 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)
}
/**
* 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 resOwnerListMap(source) {
const typeList = JSON.parse(localStorage.getItem("typeList"));
//
let resOwnerList = new Map();
let $this = this;
typeList.forEach(one1 => {
resOwnerList.set(one1.code, one1.name);
if (one1.children != null) {
one1.children.forEach(one2 => {
resOwnerList.set(one2.code, one2.name);
if (one2.children != null) {
one2.children.forEach(one3 => {
resOwnerList.set(one3.code, one3.name);
})
}
})
}
})
let name = resOwnerList.get('GC005001')
return name;
}

38
src/utils/jsencrypt.js Normal file
View File

@@ -0,0 +1,38 @@
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'
// 密钥对生成 http://web.chacuo.net/netrsakeypair
//服务端的公钥,用于加密然后发给服务端
const publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDkGQyEfRr4msmlF3kbQvr4cMze' +
'R13m+WAxUzA1ja5ggUBLOa2Xxct4IhmiO3VH/L+v5KE1ECEFOqoFjRHeBvS9Kyzc' +
'AykEIvq8MJMZ8BQCISOBd+e+WmEybOsrWCHqs1LHTS4igTxI3cIhWzQG1MCwWFXT' +
'RI8z5DkltzMsh2KGjQIDAQAB'
//自己的私钥,用于解密从服务端返回的加密串
const privateKey = 'MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAOQZDIR9GviayaUX' +
'eRtC+vhwzN5HXeb5YDFTMDWNrmCBQEs4WZfFy3giGaI7dUf8v6/koTUQIQU6qgWN' +
'Ed4G9L0rLNwDKQQi+rwwkxnwFAIhI4F3575aYTJs6ytYIeqzUsdNLiKBPEjdwiFb' +
'NAbUwLBYVdNEjzPkOSW3MyyHYoaNAgMBAAECgYBTnTsRdirk5xj0A97JN4x4diEj' +
'elXZzaCNdEk/2GgLyFWhPct8z2z+5MEwz0r20JgUCmNt6DOyjwa0cjoSgcpEvLMh' +
'boICd8OXOyUSVzpORjmdkl14HiHstWJ37UtGRwCVcn44fr3uGlJrh25z0Lrvzf61' +
'wo2m7mJTntFilKx+oQJ5APw/2DkkYQyZZIW5YjkraVPK2kpW+OgFlEBeh2br8MnT' +
'MMC13n1h/muXGIv1+RVbnMIxFRxbxxpbfKMpT6DTAacCQQDnfUZD4t5Q4ZD3ssk6' +
'0rb5a7VJaMNyl4RZ6P4jIdHSPOBtDzVMq909kICmC+SqsV4rLEo0x/8d0mLoKuyb' +
'YbSrAkA1ZYpu5i2JDjuCNzD8qxzbuPgmfmyoKO4uBhShi9Zn0sXiNV2IqyLBQbXX' +
'gtUcWU1AqkUuwJrQEIe8vjT19VTHAkAvyJQwfywU1frupmETW1uZsLoDJTTy+oO/' +
'a3DKH7kIBLjuyizeXruUcbecjufstCAUGVhX/NCUf1EbS4D7sfdxAkEAgS0pR8Np' +
'EFLh0odpNDhV1HbPBOxDSS6cyVQnUPhwEVbB5OKlCCVFw/H8wPO3q41xR9XOdowG' +
'rS1O3VXFivDGnQ=='
// 加密
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) // 对数据进行解密
}

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

@@ -0,0 +1,51 @@
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
}
}

103
src/utils/request.js Normal file
View File

@@ -0,0 +1,103 @@
import axios from 'axios'
import { Notification, MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/token'
import errorCode from '@/utils/errorCode'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
// axios中请求配置有baseURL选项表示请求URL公共部分
baseURL: process.env.VUE_APP_BASE_API,
// 超时
timeout: 10000
})
// request拦截器
service.interceptors.request.use(config => {
// 是否需要设置 token
const isToken = (config.headers || {}).isToken === false
if (getToken() && !isToken) {
config.headers['X-Access-Token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
}
// get请求映射params参数
if (config.method === 'get' && config.params) {
let url = config.url + '?';
for (const propName of Object.keys(config.params)) {
const value = config.params[propName];
var part = encodeURIComponent(propName) + "=";
if (value !== null && typeof(value) !== "undefined") {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
let params = propName + '[' + key + ']';
var subPart = encodeURIComponent(params) + "=";
url += subPart + encodeURIComponent(value[key]) + "&";
}
} else {
url += part + encodeURIComponent(value) + "&";
}
}
}
url = url.slice(0, -1);
config.params = {};
config.url = url;
}
return config
}, error => {
console.log(error)
Promise.reject(error)
})
// 响应拦截器
service.interceptors.response.use(res => {
// 未设置状态码则默认成功状态
const code = res.data.code || 200;
// 获取错误信息
const msg = errorCode[code] || res.data.msg || errorCode['default']
if (code === 401) {
MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
confirmButtonText: '重新登录',
cancelButtonText: '取消',
type: 'warning'
}
).then(() => {
store.dispatch('LogOut').then(() => {
location.href = this.webBaseUrl + '/index';
})
})
} else if (code === 500) {
Message({
message: msg,
type: 'error'
})
return Promise.reject(new Error(msg))
} else if (code !== 200) {
Notification.error({
title: msg
})
return Promise.reject('error')
} else {
return res.data
}
},
error => {
console.log('err' + 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) + "异常";
}
Message({
message: message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service

58
src/utils/scroll-to.js Normal file
View File

@@ -0,0 +1,58 @@
Math.easeInOutQuad = function(t, b, c, d) {
t /= d / 2
if (t < 1) {
return c / 2 * t * t + b
}
t--
return -c / 2 * (t * (t - 2) - 1) + b
}
// requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
var requestAnimFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60) }
})()
/**
* Because it's so fucking difficult to detect the scrolling element, just move them all
* @param {number} amount
*/
function move(amount) {
document.documentElement.scrollTop = amount
document.body.parentNode.scrollTop = amount
document.body.scrollTop = amount
}
function position() {
return document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop
}
/**
* @param {number} to
* @param {number} duration
* @param {Function} callback
*/
export function scrollTo(to, duration, callback) {
const start = position()
const change = to - start
const increment = 20
let currentTime = 0
duration = (typeof (duration) === 'undefined') ? 500 : duration
var animateScroll = function() {
// increment the time
currentTime += increment
// find the value with the quadratic in-out easing function
var val = Math.easeInOutQuad(currentTime, start, change, duration)
// move the document.body
move(val)
// do the animation unless its over
if (currentTime < duration) {
requestAnimFrame(animateScroll)
} else {
if (callback && typeof (callback) === 'function') {
// the animation is done so lets callback
callback()
}
}
}
animateScroll()
}

58
src/utils/study.js Normal file
View File

@@ -0,0 +1,58 @@
/**
* 用于处理,记录 学习的情况
*/
const studyDurationKey='xus_duration';
const studyVideoKeyPre='xus_video';
/**
* 设置视频的播放时间
* @param {} courseId
* @param {*} time
*/
const setVideoTime=function(courseId,time){
localStorage.setItem(studyVideoKeyPre+'_'+courseId,time);
}
/**
* 设置本地存储的学习时长
*/
const setStudyDuration=function(duration){
//console.log(duration,'设置时长');
localStorage.setItem(studyDurationKey,duration);
}
/**
* 清除本地记录的学习时长
*/
const clearStudyDuration=function(){
localStorage.setItem(studyDurationKey,0);
}
const getStudyDuration=function(){
let speedValue=localStorage.getItem(studyDurationKey);
if(speedValue){
//console.log(speedValue,'speedValue');
return Number(speedValue);
}else{
return 0;
}
}
/**
* 追加学习时长
* @param Number duration 学习时长(秒)
*/
const appendStudyDuration=function(duration){
let speedValue=localStorage.getItem(studyDurationKey);
if(speedValue){
localStorage.setItem(studyDurationKey,Number(speedValue)+duration);
}else{
localStorage.setItem(studyDurationKey,duration);
}
}
export default {
getStudyDuration,
setStudyDuration,
clearStudyDuration,
appendStudyDuration
}

17
src/utils/token.js Normal file
View File

@@ -0,0 +1,17 @@
import Cookies from 'vue-cookies'
//const TokenKey = 'boe-portal-token'
const TokenKey = 'token'
export function getToken() {
return Cookies.get(TokenKey)
}
export function setToken(token) {
return Cookies.set(TokenKey, token)
}
export function removeToken() {
Cookies.remove('inner')
return Cookies.remove(TokenKey)
}

221
src/utils/tools.js Normal file
View File

@@ -0,0 +1,221 @@
/**
* 对象复制
*/
export const deepCopy = (obj) => {
return JSON.parse(JSON.stringify(obj));
};
/**
* 获取url协议
* @param {Object} type
*/
export function getUrlPre(type) {
const isHttps='https:'==document.location.prototype ? true:false;
let isUrl='https';
if(isHttps){
isUrl='https';
}else{
isUrl='http';
}
return isUrl;
}
// 类型过滤
const contentTypeMaps = {
10: '视频',
20: '音频',
30: '图片',
40: '文档',
41: '图文',
50: 'scrom包',
52: '外链',
60: '作业',
61: '考试',
62: '评估',
90: '其它',
};
export function getType(type) {
let name = contentTypeMaps[type];
return name;
}
/**
* 根据文件类型后续不带点的。比如 mp4 转化为对应的资源数字
*/
export function toContentType(fileType) {
let docTypes=["pdf","doc","xls", "ppt","docx", "xlsx", "pptx"];
let type = null;
// ["doc", "xls", "ppt","docx", "xlsx", "pptx","png","txt", "pdf","jpg","gif","bmp","mp4","mp3"]
if (fileType === "mp4") {
type = 10;
} else if (fileType === "mp3") {
type = 20;
} else if (fileType === "jpg" ||fileType === "png" ||fileType === "gif") {
type = 30;
} else if (docTypes.indexOf(fileType)>-1){
type = 40;
} else {
type = 90;
}
return type;
}
// 10微课21在线课(直播)20:在线课( 录播)30:面授课40:混合式,
// export function courseType(type) {
// const maps = {
// 10: '微课',
// 21: '在线课(直播)',
// 20: '在线课(录播)',
// 30: '面授课',
// 40: '混合式',
// };
// return maps[type];
// }
export function courseType(type) {
const maps = {
10: '微课',
21: '在线课(直播)',
20: '录播课',
30: '线下课',
40: '学习项目',
};
return maps[type];
}
/**
* 把日期格式化为显示时间yyyy-MM-dd HH:mm:ss
* @param {Object} date
*/
export function formatDate(date){
var year = date.getFullYear(),
month = date.getMonth() + 1,//月份是从0开始的
day = date.getDate(),
hour = date.getHours(),
min = date.getMinutes(),
sec = date.getSeconds();
if(month<10){month='0'+month}
if(day<10){day='0'+day}
if(hour<10){hour='0'+hour}
if(min<10){min='0'+min}
if(sec<10){sec='0'+sec}
var newTime = year + '-' +
month + '-' +
day + ' ' +
hour + ':' +
min + ':' +
sec;
return newTime;
}
export function numberToLetter(x){ //此方法和移到utils中去
let s = "";
while (x > 0) {
let m = x % 26;
m = m === 0 ? (m = 26) : m;
s = String.fromCharCode(96 + parseInt(m)) + s;
x = (x - m) / 26;
}
return s.toUpperCase();
}
export function testType(type) { //此方法移到tools中
let name = '';
switch (type) {
case 101:
name = '单选';
break;
case 102:
name = '多选';
break;
case 103:
name = '判断';
break;
}
return name;
}
export function examType(type) { //此方法移到tools中
let name = '';
switch (type) {
case 1:
name = '单选';
break;
case 2:
name = '多选';
break;
case 3:
name = '判断';
break;
}
return name;
}
export function correctJudgment(ditem) {
let judgment = false;
if(ditem.type == 101 || ditem.type == 103) {
ditem.options.forEach(item=>{
if(item.answer){
if(item.id == ditem.userAnswer) {
judgment = true;
} else{
judgment = false;
}
}
})
} else {
ditem.options.forEach(item=>{
if(item.answer == item.isCheck){
judgment = true;
}else{
judgment = false;
}
})
}
return judgment;
}
export function toScore(score) {
if (!score) {
return '0';
}
if((''+score).indexOf('.')>-1){
return score.toFixed(1);
}else{
return score+'.0';
}
}
export function toScoreTow(score) {// 返回两位小数
if (!score) {
return '0';
}
if((''+score).indexOf('.')>-1){
return score.toFixed(2);
}else{
return score+'.00';
}
}
/**
* 数组互换位置
* @param {array} arr 数组
* @param {number} index1 添加项目的位置
* @param {number} index2 删除项目的位置
* index1和index2分别是两个数组的索引值即是两个要交换元素位置的索引值如15就是数组中下标为1和5的两个元素交换位置
*/
export function swapArray(arr, index1, index2) {
arr[index1] = arr.splice(index2, 1, arr[index1])[0];
return arr;
}
/**
* 头像文字
* @param {*} text
* @returns
*/
export function userAvatarText(text){
if(text){
let len=text.length;
if(len>2){
text=text.substring(len-2);
}
}
return text;
}

92
src/utils/validate.js Normal file
View File

@@ -0,0 +1,92 @@
/**
* @param {string} path
* @returns {Boolean}
*/
export function isExternal(path) {
return /^(https?:|mailto:|tel:)/.test(path)
}
/**
* @param {string} mobile
* @returns {Boolean}
*/
export function validMobile(str) {
const reg = /^0?1[3|4|5|6|7|8][0-9]\d{8}$/;
return reg.test(str)
}
/**
* @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)
}

63
src/utils/warterMark.js Normal file
View File

@@ -0,0 +1,63 @@
let watermark = {}
let setWatermark = (text, sourceBody) => {
//let id = Math.random() * 10000 + '-' + Math.random() * 10000 + '/' + Math.random() * 10000
let id='boedx-water-mark';
if (document.getElementById(id) !== null) {
document.body.removeChild(document.getElementById(id))
}
let can = document.createElement('canvas')
can.width = 400 //设置水印之间的左右间距
can.height = 240 //设置水印之间的上下间距
let cans = can.getContext('2d')
cans.rotate(-20 * Math.PI / 180)
cans.font = '18px Vedana'
cans.fillStyle = 'rgba(233, 233, 233, 0.5)'
cans.textAlign = 'left'
cans.textBaseline = 'Middle'
cans.fillText(text, can.width / 20, can.height)
let water_div = document.createElement('div');
water_div.id = id
water_div.style.pointerEvents = 'none'
water_div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
if (sourceBody) {
water_div.style.width = '100%'
water_div.style.height = '100%'
sourceBody.appendChild(water_div)
} else {
water_div.style.top = '3px'
water_div.style.left = '0px'
water_div.style.position = 'fixed'
water_div.style.zIndex = '10'
water_div.style.width = document.documentElement.clientWidth + 'px'
water_div.style.height = document.documentElement.clientHeight + 'px'
document.body.appendChild(water_div)
}
return id
}
/**
* 该方法只允许调用一次
* @param:
* @text == 水印内容
* @sourceBody == 水印添加在哪里不传就是body
* */
watermark.set = (text, sourceBody) => {
let id = setWatermark(text, sourceBody)
setInterval(() => {
if (document.getElementById(id) === null) {
id = setWatermark(text, sourceBody)
}
}, 2000)
window.onresize = () => {
setWatermark(text, sourceBody)
}
}
export default watermark

233
src/utils/xajax.js Normal file
View File

@@ -0,0 +1,233 @@
import axios from 'axios'
import qs from 'qs'
import { Notification, MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/token'
import errorCode from '@/utils/errorCode'
/**
*request请求 axios.request(config)
*requestJson请求 axios.request(config)
*get请求 axios.get(url[, config])
*post请求 axios.post(url[, data[, config]])
*postJson请求 axios.post(url[, data[, config]])
*put请求 axios.put(url[, data[, config]])
*putJson请求 axios.put(url[, data[, config]])
*patch请求 axios.patch(url[, data[, config]])
*patchJson请求 axios.patch(url[, data[, config]])
*delete请求 axios.delete(url[, config])
*/
//const ReLoginUrl="/login";
const ReLoginUrl=process.env.VUE_APP_LOGIN_URL;
const TokenName='XBOE-Access-Token';
/**axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'**/
//只是用于发送json对象数据时使用post,put,patch
const jsonRequest=axios.create({
headers:{'Content-Type':'application/json;charset=utf-8'},
// axios中请求配置有baseURL选项表示请求URL公共部分
baseURL: process.env.VUE_APP_BASE_API,
//超时
timeout: 10000,
});
//发送json对象的拦截器
jsonRequest.interceptors.request.use(config => {
//是否需要设置 token
const isToken = (config.headers || {}).isToken === false
if (getToken() && !isToken) {
config.headers[TokenName] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
}
return config
}, error => {
console.log(error)
Promise.reject(error)
})
// 响应拦截器
jsonRequest.interceptors.response.use(res => {
const code = res.data.status || 200;
if(code===200){
return res.data
}else{
if(code == 6001){ //针对于老系统的处理
store.dispatch('LogOut').then(() => {
location.href = ReLoginUrl;
})
}else if(code === 401){
store.dispatch('LogOut').then(() => {
location.href = ReLoginUrl;
})
}else if(code === 402){
store.dispatch('LogOut').then(() => {
location.href = ReLoginUrl;
})
}else if(code===403){
var msg='当前操作没有权限';
Message({message: msg, type: 'error'});
return Promise.reject(new Error(msg))
//return res.data;
}else if(code===302){
location.href = ReLoginUrl;
}else{
//Message({message: res.data.message, type: 'error'});
//console.log('err:' + res.data.error);
//return Promise.reject(new Error(res.data.message))
return res.data;
}
}
},
error => {
console.log('err' + error)
let { message } = error;
if (message == "Network Error") {
message = "后端接口连接异常";
}
else if (message.includes("timeout")) {
message = "系统接口请求超时";
//location.href = this.webBaseUrl + ReLoginUrl;
}
else if (message.includes("Request failed with status code")) {
message = "系统接口" + message.substr(message.length - 3) + "异常";
}
Message({
message: message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
//用于普通的发送请求
const formRequest=axios.create({
headers:{'Content-Type':'application/x-www-form-urlencoded'},
// axios中请求配置有baseURL选项表示请求URL公共部分
baseURL: process.env.VUE_APP_BASE_API,
//超时
timeout: 10000,
})
//发送json对象的拦截器
formRequest.interceptors.request.use(config => {
//是否需要设置 token
const isToken = (config.headers || {}).isToken === false
if (getToken() && !isToken) {
config.headers[TokenName] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
}
return config
}, error => {
console.log(error)
Promise.reject(error)
});
formRequest.interceptors.response.use(res => {
const code = res.data.status || 200;
if(code===200){
return res.data
}else{
if(code == 6001){ //针对于老系统的处理,因为老系统是字符串,所以这里不使用三等于号
store.dispatch('LogOut').then(() => {
location.href = ReLoginUrl;
})
}else if(code === 401){
store.dispatch('LogOut').then(() => {
location.href = ReLoginUrl;
})
}else if(code === 402){
store.dispatch('LogOut').then(() => {
location.href = ReLoginUrl;
})
}else if(code===403){
var msg='当前操作没有权限';
Message({message: msg, type: 'error'});
return Promise.reject(new Error(msg))
}else if(code===302){
location.href = ReLoginUrl;
}else{
//Message({message: res.data.message, type: 'error'});
//console.log('err' + res.data.error);
//return Promise.reject(new Error(res.data.message))
return res.data;//返回给用户做业务处理
}
}
},
error => {
console.log('err' + error)
let { message } = error;
if (message == "Network Error") {
message = "后端接口连接异常";
}
else if (message.includes("timeout")) {
message = "系统接口请求超时";
//location.href = this.webBaseUrl + ReLoginUrl;
}
else if (message.includes("Request failed with status code")) {
message = "系统接口" + message.substr(message.length - 3) + "异常";
}
Message({
message: message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
//request请求
const request=function(cfg){
if(cfg.data){
cfg.data=qs.stringify(cfg.data);
}
};
//requestJson请求
const requestJson=jsonRequest.request;
//get请求
const get=formRequest.request;
//post请求
const post=function(url,data,config){
if(data){
data=qs.stringify(data);
}
return formRequest.post(url,data,config);
}
//post请求
const postForm=function(url,data,config){
return formRequest.post(url,data,config);
}
//postJson请求
const postJson=jsonRequest.post;
//put请求
const put=function(url,data,config){
if(data){
data=qs.stringify(data);
}
return formRequest.put(url,data,config);
}
//putJson请求
const putJson=jsonRequest.put;
//patch请求
const patch=function(url,data,config){
if(data){
data=qs.stringify(data);
}
return formRequest.patch(url,data,config);
}
//patchJson请求
const patchJson=jsonRequest.patch;
//delete请求
const del=formRequest.delete;
export default {
request,
requestJson,
get,
post,
postJson,
put,
putJson,
patch,
patchJson,
del,
postForm
}

40
src/utils/zipdownload.js Normal file
View File

@@ -0,0 +1,40 @@
import axios from 'axios'
import { getToken } from '@/utils/token'
const mimeMap = {
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
zip: 'application/zip'
}
const baseUrl = process.env.VUE_APP_BASE_API
export function downLoadZip(str, filename) {
var url = baseUrl + str
axios({
method: 'get',
url: url,
responseType: 'blob',
headers: { 'Authorization': 'Bearer ' + getToken() }
}).then(res => {
resolveBlob(res, mimeMap.zip)
})
}
/**
* 解析blob响应内容并下载
* @param {*} res blob响应内容
* @param {String} mimeType MIME类型
*/
export function resolveBlob(res, mimeType) {
const aLink = document.createElement('a')
var blob = new Blob([res.data], { type: mimeType })
// //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
var contentDisposition = decodeURI(res.headers['content-disposition'])
var result = patt.exec(contentDisposition)
var fileName = result[1]
fileName = fileName.replace(/\"/g, '')
aLink.href = URL.createObjectURL(blob)
aLink.setAttribute('download', fileName) // 设置下载文件名称
document.body.appendChild(aLink)
aLink.click()
document.body.appendChild(aLink)
}