This commit is contained in:
ln1778 2024-05-07 11:51:58 +08:00
parent e9bc6a2c35
commit 4c0adafbbf
37 changed files with 1854 additions and 20 deletions

BIN
.DS_Store vendored

Binary file not shown.

View File

@ -652,7 +652,7 @@ export default {
right: 0px;
height: 18px;
width: 22px;
background: url(https://aiguovip2020.oss-cn-shenzhen.aliyuncs.com/static/assets/img/xiaogou.png) 0px bottom;
background: url(https://aiguovip2020.oss-cn-shenzhen.aliyuncs.com/static/assets/xiaogou.png) 0px bottom;
background-size: 100%;
display: none;
}

View File

@ -49,6 +49,7 @@
<script>
import QRCode from "qrcodejs2";
export default {
name: "erpXylog",
data() {
return {
src: ``,

BIN
assets/noimg.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

View File

@ -73,7 +73,7 @@
<img
v-else
style="float: left; height: 70px"
src="../../assets/img/noimg.jpg"
src="./../assets/noimg.jpg"
/>
</div>
<ul class="info-right">
@ -227,7 +227,7 @@
<script>
import Sortable from "sortablejs";
import xylog from "./Dialog/xyqualitydialog";
import xylog from "./../Dialog/xyqualitydialog";
export default {
name:"erpTable",
components: {

View File

@ -74,7 +74,7 @@
<img v-if="row['img']" style="height: 350px" :src="row['img']" />
<img v-if="row['img']" slot="reference" style="float: left; height: 70px" :src="row['img']" />
</el-popover>
<img v-else style="float: left; height: 70px" src="../../assets/img/noimg.jpg" />
<img v-else style="float: left; height: 70px" src="./../assets/noimg.jpg" />
</div>
<ul class="info-right">
<li>
@ -247,18 +247,18 @@
</template>
</vxe-column>
</vxe-table>
<xylog :xylogdialog-visible="xylogdialogVisible" :xylogid="xylogid" :xylogtype="xylogtype"
<erp-xylog :xylogdialog-visible="xylogdialogVisible" :xylogid="xylogid" :xylogtype="xylogtype"
@xylogdialog="xylogdialog" />
</div>
</template>
<script>
import Sortable from "sortablejs";
import xylog from "./../Dialog/xyqualitydialog";
import erpXylog from "./../Dialog/xyqualitydialog";
export default {
name:"erpXyTable",
components: {
xylog,
erpXylog,
},
data() {
return {

View File

@ -120,7 +120,7 @@
<img
v-else
style="float: left; height: 70px"
src="../../assets/img/noimg.jpg"
src="./../assets/noimg.jpg"
/>
</div>
<ul class="info-right">
@ -405,7 +405,7 @@
</template>
</vxe-column>
</vxe-table>
<xylog
<erp-xylog
:xylogdialog-visible="xylogdialogVisible"
:xylogid="xylogid"
:xylogtype="xylogtype"
@ -416,11 +416,11 @@
<script>
import Sortable from "sortablejs";
import xylog from "./../Dialog/xyqualitydialog";
import erpXylog from "./../Dialog/xyqualitydialog";
export default {
name:"erpYsTable",
components: {
xylog,
erpXylog,
},
data() {
return {

View File

@ -1,6 +1,6 @@
{
"name": "erp-element-ui",
"version": "1.0.11",
"version": "1.0.16",
"description": "",
"main": "index.js",
"scripts": {

View File

@ -1,4 +1,54 @@
//封装
import { Decimal } from 'decimal.js'
export function add(){
// 加
export function add (x, y) {
if (!x) {
x = 0
}
if (!y) {
y = 0
}
const xx = new Decimal(x)
const yy = new Decimal(y)
return xx.plus(yy).toNumber()
}
// 减
export function reduce (x, y) {
if (!x) {
x = 0
}
if (!y) {
y = 0
}
const xx = new Decimal(x)
const yy = new Decimal(y)
return xx.minus(yy).toNumber()
}
// 乘
export function ride (x, y) {
if (!x) {
x = 0
}
if (!y) {
y = 0
}
const xx = new Decimal(x)
const yy = new Decimal(y)
return xx.mul(yy).toNumber()
}
// 除
export function except (x, y) {
if (!x) {
x = 0
}
if (!y) {
y = 0
}
const xx = new Decimal(x)
const yy = new Decimal(y)
return xx.div(yy).toNumber()
}

13
utils/Set.js Normal file
View File

@ -0,0 +1,13 @@
export function hasDuplicate(arr) {
// 将数组转换为Set
var set = new Set(arr)
console.log(set)
const Array = arr.filter((item, index) => arr.indexOf(item) !== index)
console.log(Array)
// 如果Set的长度小于数组的长度说明有重复的值
if (set.size < arr.length) {
return { arr: Array, status: true }
} else {
return { arr: Array, status: false }
}
}

43
utils/alioss.js Normal file
View File

@ -0,0 +1,43 @@
import axios from "axios"; //引入axios
import { get_oss_sign_aliyun } from '@/api/user';
const instance = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 300000,
});
// let baseURL = process.env.BASE_URL.toString();
//这里根据自己项目接口的位置自行设定
let baseURL = process.env.VUE_APP_BASE_API;
// if (process.env.NODE_ENV == "production") {
// baseURL = "http://1xx.1xx.1xx.1xx/hyr";
// }
// instance.defaults.baseURL = baseURL; //baseURL用于自动切换本地环境接口和生产环境接口
instance.defaults.headers.post["Content-Type"] ="multipart/form-data";
// instance.defaults.headers.post["Access-Control-Allow-Origin"] = "*";
// instance.defaults.withCredentials = false; // 携带cookie
//上传附件axios接口封装
const upload = {
async uploadFile( payload,v, cd) {
let res = await get_oss_sign_aliyun({type:v})
payload.append("policy", res.datas.policy);
payload.append("OSSAccessKeyId", res.datas.accessid);
payload.append("signature", res.datas.signature);
payload.append("success_action_status", '200');
return instance({
url: `https://${res.datas.host}`,
method: "post",
data: payload,
onUploadProgress: function(progressEvent) {
if (progressEvent.lengthComputable) {
cd(progressEvent);
}
},
// cancelToken: cancelToken,
});
},
}
export {
upload,
axios,
}

104
utils/aliyun.oss.client.js Normal file
View File

@ -0,0 +1,104 @@
/**
* 阿里云oss上传工具
*/
import { get_oss_sign_aliyun } from '@/api/user'
const OSS = require('ali-oss')
const config = {
region: 'oss-cn-shenzhen',
accessKeyId: 'LTAIyZIrTMnMYzZ8',
accessKeySecret: 'bte644kZ70psfTenXE0IbSSQk040u1',
// accessKeySecret: '1',
policy: '',
bucket: 'aiguovip2020'
}
/**
* 配置
*/
const init = async(v) => {
const res = await get_oss_sign_aliyun({ type: v })
config.region = res.datas.region
config.accessKeyId = res.datas.accessid
config.signature = res.datas.signature
config.policy = res.datas.policy
config.bucket = res.datas.bucket
console.log(config)
return new OSS(config)
}
/**
* 生成uuid
*/
const guid = () => {
const S4 = () => {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}
return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
}
/**
* 修改文件名字
*/
const fileName = (file) => {
const arr = file.name.split('.')
var uuid = 'oss' + guid()
if (arr.length > 1) {
return uuid + '.' + arr[arr.length - 1]
} else {
return uuid
}
}
/**
* 上传文件
*/
const ossPut = (file, dir) => {
return new Promise((resolve, reject) => {
const objectName = fileName(file)
init().put(dir + objectName, file).then(({ res, url }) => {
if (res && res.status == 200) {
resolve(res, url)
}
}).catch((err) => {
reject(err)
})
})
}
// 直接调取oss函数返回URL结果
function uploadOSS(file) {
return new Promise(async(resolve, reject) => {
const fileName = fileName(file)
// let client = new OSS({
// region: OSSConfig.ossParams.region,
// accessKeyId: OSSConfig.ossParams.accessKeyId,
// accessKeySecret: OSSConfig.ossParams.accessKeySecret,
// bucket: OSSConfig.ossParams.bucket,
// secure: true
// })
const res = await init().multipartUpload(dir + fileName, file)
if (res.name) {
resolve({
fileName: file.name,
url: `${OSSConfig.uploadHost}/${fileName}`
})
} else {
reject('OSS上传失败')
}
})
}
/**
* 下载文件
*/
const ossGet = (name) => {
return new Promise((resolve, reject) => {
init().get(name).then(({ res }) => {
if (res && res.status == 200) {
resolve(res)
}
}).catch((err) => {
reject(err)
})
})
}
export default { ossPut, ossGet, uploadOSS, init }

84
utils/asyncRouter.js Normal file
View File

@ -0,0 +1,84 @@
/*
* @Author: ckycjwds 1240973496@qq.com
* @Date: 2022-11-22 17:56:39
* @LastEditors: ckycjwds 1240973496@qq.com
* @LastEditTime: 2023-03-09 11:24:50
* @FilePath: \aiguo_erp_vue\src\utils\asyncRouter.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
// 引入路由文件这种的公共路由
// import { constantRoutes } from '../router';
// Layout 组件是项目中的主页面切换路由时仅切换Layout中的组件
import Layout from '@/layout'
// import View from '@/layout/View.vue';
import Views from '../layout/View.vue'
// const Views = require('@/layout/View.vue')
import { asyncRoutes, constantRoutes } from '@/router'
export function getAsyncRoutes(routes) {
const res = []
// 定义路由中需要的自定名
const keys = ['path', 'name', 'child', 'redirect', 'meta', 'hidden']
if(routes){
// 遍历路由数组去重组可用的路由
routes.forEach(item => {
// console.log(item)
// this.$set(item, 'meta', { })
const newItem = {}
if (item.name != '控制台菜单(默认存在)') {
if (item.component) {
// 判断 item.component 是否等于 'Layout',若是则直接替换成引入的 Layout 组件
if (item.component === 'Layout') {
newItem.component = Layout
newItem.redirect = item.path
} else if (item.component === 'View' && item.level == 2) { // 判断 item.component 是否等于 'View',若是则直接替换成引入的 View 组件,用于二级分类使用
newItem.component = Views
newItem.redirect = item.child && item.child[0].path
} else {
newItem.component = (resolve) => require([`@/views${item.component}`], resolve)
// newItem.component = (resolve) => require([`@/views${item.component}`], resolve)
// newItem.component = () => import(`@/views${item.component}`)
// newItem.component = (resolve) => require([`@/views/Warehousing/Storageentryworkbench`], resolve)
}
}
for (const key in item) {
if (keys.includes(key)) {
newItem[key] = item[key]
}
newItem.meta = { title: item.name }
if (item.no_cache && item.no_cache == '0') {
newItem.meta.noCache = true
} else {
delete newItem.noCache
}
if (item.hidden && item.hidden == '0') {
newItem.hidden = true
} else {
delete newItem.hidden
}
if (item.ico) {
newItem.meta.icon = item.ico
}
newItem.name = item.code
}
// 若遍历的当前路由存在子路由,需要对子路由进行递归遍历
if (newItem.child && newItem.child.length) {
if (newItem.child.every((e) => { return e.level == 1 })) {
newItem.children = getAsyncRoutes(item.child)
} else if (newItem.child.every((e) => { return e.level == 2 })) {
newItem.children = getAsyncRoutes(item.child)
} else if (newItem.child.every((e) => { return e.level == 3 }) && newItem.child.every((e) => { return e.group != 2 })) { // newItem.child.every((e)=>{return e.group!=2}) 防止二级下只有按钮
newItem.children = getAsyncRoutes(item.child)
}
}
delete newItem.child;
newItem.meta.keepAlive = true
res.push(newItem);
}
})
}
// console.log(res)
return res
}

15
utils/auth.js Normal file
View File

@ -0,0 +1,15 @@
import Cookies from 'js-cookie'
const TokenKey = 'token'
export function getToken() {
return Cookies.get(TokenKey)
}
export function setToken(token) {
return Cookies.set(TokenKey, token)
}
export function removeToken() {
return Cookies.remove(TokenKey)
}

34
utils/autoTableHeight.js Normal file
View File

@ -0,0 +1,34 @@
/*
* @Author: your name
* @Date: 2021-05-06 17:17:43
* @LastEditTime: 2021-06-29 17:27:21
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \aiguo_erp_vue\src\utils\autoTableHeight.js
*/
//获取浏览器窗口高度,处理Element的Table组件的高度问题height只能是数字或者字符串
function autoTableHeight() {
var winHeight = 0;
if (window.innerHeight) {
winHeight = window.innerHeight;
} else if (document.body && document.body.clientHeight) {
winHeight = document.body.clientHeight;
} //通过深入Document内部对body进行检测获取浏览器窗口高度
if (document.documentElement && document.documentElement.clientHeight) {
winHeight = document.documentElement.clientHeight;
}
// 370 是顶部和底部导航以及部分自定义布局 相当于用js实现了 height: calc(100vh - 260px); 的效果
return winHeight - 370;
}
//浏览器窗口变化时
window.onresize = function() {
autoTableHeight();
};
//浏览器重新加载时
window.onload = function() {
autoTableHeight();
};
export default autoTableHeight;

8
utils/cancelToken.js Normal file
View File

@ -0,0 +1,8 @@
class cancelClass {
static cancelRequest = {
source: {
token:null,
cancel:null
}
}}
export default cancelClass

16
utils/common.js Normal file
View File

@ -0,0 +1,16 @@
!(function(doc, win) {
var docEl = doc.documentElement
var resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize'
var recalc = function() {
var clientWidth = docEl.clientWidth
if (!clientWidth) return
if (clientWidth >= 750) {
docEl.style.fontSize = '100px'
} else {
docEl.style.fontSize = 100 * (clientWidth / 750) + 'px'
}
}
if (!doc.addEventListener) return
win.addEventListener(resizeEvt, recalc, false)
doc.addEventListener('DOMContentLoaded', recalc, false)
}(document, window))

22
utils/directive.js Normal file
View File

@ -0,0 +1,22 @@
import Vue from 'vue';
// 自定义指令实现按下enter后光标自动跳转下一个输入框
Vue.directive('enterNextInput', {
inserted: function (el) {
el.addEventListener("keypress",function(e){
e = e || window.event;
let charcode = typeof e.charCode == 'number' ? e.charCode : e.keyCode;
if(charcode == 13){
var dom = document.querySelectorAll(".el-input__inner")
for (var i = 0; i < dom.length; i++) {
if (dom[i] == document.activeElement) {
if (i==dom.length) {
return
}
dom[i+1].focus()
return
}
}
}
});
},
});

10
utils/get-page-title.js Normal file
View File

@ -0,0 +1,10 @@
import defaultSettings from '@/settings'
const title = defaultSettings.title || 'Vue Admin Template'
export default function getPageTitle(pageTitle) {
if (pageTitle) {
return `${pageTitle} - ${title}`
}
return `${title}`
}

37
utils/htmlToPdf.js Normal file
View File

@ -0,0 +1,37 @@
// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default{
install (Vue, options) {
Vue.prototype.getPdf = function () {
var title = this.htmlTitle
html2Canvas(document.querySelector('#pdfDom'), {
allowTaint: true
}).then(function (canvas) {
let contentWidth = canvas.width
let contentHeight = canvas.height
let pageHeight = contentWidth / 592.28 * 841.89
let leftHeight = contentHeight
let position = 0
let imgWidth = 595.28
let imgHeight = 592.28 / contentWidth * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 1.0)
let PDF = new JsPDF('', 'pt', 'a4')
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
if (leftHeight > 0) {
PDF.addPage()
}
}
}
PDF.save(title + '.pdf')
}
)
}
}
}

75
utils/htmlToPdfJQ.js Normal file
View File

@ -0,0 +1,75 @@
/* eslint-disable */
//使用JQuery方式写的。
import html2canvas from 'html2canvas';
import JsPDF from 'jspdf';
// import $ from 'jquery';
// console.log($, '这是什么什么');
function download(ele){
var element = $("#demo"); // 这个dom元素是要导出pdf的div容器
console.log(element,'1212122');
// var element = ele; // 这个dom元素是要导出pdf的div容器
var w = element.width(); // 获得该容器的宽
var h = element.height(); // 获得该容器的高
var offsetTop = element.offset().top; // 获得该容器到文档顶部的距离
var offsetLeft = element.offset().left; // 获得该容器到文档最左的距离
console.log(offsetTop,'------',offsetLeft);
var canvas = document.createElement("canvas");
var abs = 0;
var win_i = $(window).width(); // 获得当前可视窗口的宽度(不包含滚动条)
var win_o = window.innerWidth; // 获得当前窗口的宽度(包含滚动条)
console.log(canvas, abs, win_i, win_o);
if(win_o>win_i){
abs = (win_o - win_i)/2; // 获得滚动条长度的一半
}
canvas.width = w * 2; // 将画布宽&&高放大两倍
canvas.height = h * 2;
var context = canvas.getContext("2d");
context.scale(2, 2);
context.translate(-offsetLeft-abs,-offsetTop);
// 这里默认横向没有滚动条的情况因为offset.left(),有无滚动条的时候存在差值,因此
// translate的时候要把这个差值去掉
// html2canvas(element).then( (canvas)=>{ //报错
html2canvas(element[0]).then( (canvas)=>{
var contentWidth = canvas.width;
var contentHeight = canvas.height;
//一页pdf显示html页面生成的canvas高度;
var pageHeight = contentWidth / 592.28 * 841.89;
//未生成pdf的html页面高度
var leftHeight = contentHeight;
//页面偏移
var position = 0;
//a4纸的尺寸[595.28,841.89]html页面生成的canvas在pdf中图片的宽高
var imgWidth = 595.28;
var imgHeight = 592.28/contentWidth * contentHeight;
var pageData = canvas.toDataURL('image/jpeg', 1.0);
var pdf = new JsPDF('', 'pt', 'a4');
//有两个高度需要区分一个是html页面的实际高度和生成pdf的页面高度(841.89)
//当内容未超过pdf一页显示的范围无需分页
if (leftHeight < pageHeight) {
pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
} else { // 分页
while(leftHeight > 0) {
pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight;
position -= 841.89;
//避免添加空白页
if(leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save('我的简历.pdf');
})
}
export default {
download
}

1
utils/import.js Normal file
View File

@ -0,0 +1 @@
module.exports = file => () => import(file)

207
utils/indedDb.js Normal file
View File

@ -0,0 +1,207 @@
/**
* 封装的方法以及用法
* 打开数据库
*/
export function openDB(dbName, storeName, version = 1) {
return new Promise((resolve, reject) => {
let indexedDB = window.indexedDB
let db
const request = indexedDB.open(dbName, version)
request.onsuccess = function(event) {
db = event.target.result // 数据库对象
resolve(db)
}
request.onerror = function(event) {
reject(event)
}
request.onupgradeneeded = function(event) {
// 数据库创建或升级的时候会触发
console.log('onupgradeneeded')
db = event.target.result // 数据库对象
let objectStore
if (!db.objectStoreNames.contains(storeName)) {
objectStore = db.createObjectStore(storeName, { keyPath: 'id' }) // 创建表
// objectStore.createIndex('name', 'name', { unique: true }) // 创建索引 可以让你搜索任意字段
}
}
})
}
/**
* 新增数据
*/
export function addData(db, storeName, data) {
return new Promise((resolve, reject) => {
let request = db.transaction([storeName], 'readwrite') // 事务对象 指定表格名称和操作模式("只读"或"读写"
.objectStore(storeName) // 仓库对象
.add(data)
request.onsuccess = function(event) {
resolve(event)
}
request.onerror = function(event) {
throw new Error(event.target.error)
reject(event)
}
})
}
/**
* 通过主键读取数据
*/
export function getDataByKey(db, storeName, key) {
return new Promise((resolve, reject) => {
let transaction = db.transaction([storeName]) // 事务
let objectStore = transaction.objectStore(storeName) // 仓库对象
let request = objectStore.get(key)
request.onerror = function(event) {
reject(event)
}
request.onsuccess = function(event) {
resolve(request.result)
}
})
}
/**
* 通过游标读取数据
*/
export function cursorGetData(db, storeName) {
let list = []
let store = db.transaction(storeName, 'readwrite') // 事务
.objectStore(storeName) // 仓库对象
let request = store.openCursor() // 指针对象
return new Promise((resolve, reject) => {
request.onsuccess = function(e) {
let cursor = e.target.result
if (cursor) {
// 必须要检查
list.push(cursor.value)
cursor.continue() // 遍历了存储对象中的所有内容
} else {
resolve(list)
}
}
request.onerror = function(e) {
reject(e)
}
})
}
/**
* 通过索引读取数据
*/
export function getDataByIndex(db, storeName, indexName, indexValue) {
let store = db.transaction(storeName, 'readwrite').objectStore(storeName)
let request = store.index(indexName).get(indexValue)
return new Promise((resolve, reject) => {
request.onerror = function(e) {
reject(e)
}
request.onsuccess = function(e) {
resolve(e.target.result)
}
})
}
/**
* 通过索引和游标查询记录
*/
export function cursorGetDataByIndex(db, storeName, indexName, indexValue) {
let list = []
let store = db.transaction(storeName, 'readwrite').objectStore(storeName) // 仓库对象
let request = store.index(indexName) // 索引对象
.openCursor(IDBKeyRange.only(indexValue)) // 指针对象
return new Promise((resolve, reject) => {
request.onsuccess = function(e) {
let cursor = e.target.result
if (cursor) {
list.push(cursor.value)
cursor.continue() // 遍历了存储对象中的所有内容
} else {
resolve(list)
}
}
request.onerror = function(ev) {
reject(ev)
}
})
}
/**
* 更新数据
*/
export function updateDB(db, storeName, data) {
let request = db.transaction([storeName], 'readwrite') // 事务对象
.objectStore(storeName) // 仓库对象
.put(data)
return new Promise((resolve, reject) => {
request.onsuccess = function(ev) {
resolve(ev)
}
request.onerror = function(ev) {
resolve(ev)
}
})
}
/**
* 删除数据
*/
export function deleteDB(db, storeName, id) {
let request = db.transaction([storeName], 'readwrite').objectStore(storeName).delete(id)
return new Promise((resolve, reject) => {
request.onsuccess = function(ev) {
resolve(ev)
}
request.onerror = function(ev) {
resolve(ev)
}
})
}
/**
* 删除数据库
*/
export function deleteDBAll(dbName) {
console.log(dbName)
let deleteRequest = window.indexedDB.deleteDatabase(dbName)
return new Promise((resolve, reject) => {
deleteRequest.onerror = function(event) {
console.log('删除失败')
}
deleteRequest.onsuccess = function(event) {
console.log('删除成功')
}
})
}
/**
* 关闭数据库
*/
export function closeDB(db) {
db.close()
console.log('数据库已关闭')
}
export default {
openDB,
addData,
getDataByKey,
cursorGetData,
getDataByIndex,
cursorGetDataByIndex,
updateDB,
deleteDB,
deleteDBAll,
closeDB
}

200
utils/index.js Normal file
View File

@ -0,0 +1,200 @@
/**
* Created by PanJiaChen on 16/11/18.
*/
/**
* Parse the time to string
* @param {(Object|string|number)} time
* @param {string} cFormat
* @returns {string | null}
*/
export function parseTime(time, cFormat) {
if (arguments.length === 0 || !time) {
return null;
}
const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
let date;
if (typeof time === "object") {
date = time;
} else {
if (typeof time === "string") {
if (/^[0-9]+$/.test(time)) {
// support "1548221490638"
time = parseInt(time);
} else {
// support safari
// https://stackoverflow.com/questions/4310953/invalid-date-in-safari
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(/{([ymdhisa])+}/g, (result, key) => {
const value = formatObj[key];
// Note: getDay() returns 0 on Sunday
if (key === "a") {
return ["日", "一", "二", "三", "四", "五", "六"][value];
}
return value.toString().padStart(2, "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 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;
}
// 时间戳减去当前时间的天数
export function parseTian(time) {
// 假设你的时间戳为1609459200000
let timestamp = time;
// 将时间戳转换为日期对象
let date = new Date(timestamp);
// 获取当前日期
let now = new Date();
// 计算两个日期之间的毫秒数
let diff = date - now;
// 将毫秒数转换为天数
let days = Math.floor(diff / (1000 * 60 * 60 * 24));
return days;
}
export function calc_day(time) {
let timestamp = time;
// 将时间戳转换为日期对象
let date = new Date(timestamp);
// 获取当前日期
let now = new Date();
// 计算两个日期之间的毫秒数
let diff = now - date;
// 将时间戳相减获得差值(毫秒数)
/**
* @desc 毫秒数除以1000就转为秒数
* @desc 秒数除以60后取整就是分钟因为1分钟等于60秒
* @desc 秒数除以3600后取整就是小时因为1小时等于3600秒
* @desc 小时数除以24后取整就是相差的天数
*/
var day = diff / 1000 / 60 / 60 / 24;
return parseInt(day);
}
//2023-09-18 10:33:45 输出2023-9-18
export function parseDays(time) {
const dateTimeStr = time;
const date = new Date(dateTimeStr);
const year = date.getFullYear();
const month = date.getMonth() + 1; // 注意月份是从0开始的因此需要加1
const day = date.getDate();
const formattedDate = `${year}-${month}-${day}`;
return formattedDate;
}
export function getTimeDays(time) {
var timestamp = time;
var date = new Date(timestamp);
var year = date.getFullYear();
var month = ("0" + (date.getMonth() + 1)).slice(-2); // 注意JavaScript中月份是从0开始的所以我们需要+1
var day = ("0" + date.getDate()).slice(-2);
var hours = ("0" + date.getHours()).slice(-2);
var minutes = ("0" + date.getMinutes()).slice(-2);
var seconds = ("0" + date.getSeconds()).slice(-2);
return year + '-' + month + '-' + day;
// console.log(
// "Date: " +
// year +
// "-" +
// month +
// "-" +
// day +
// " " +
// hours +
// ":" +
// minutes +
// ":" +
// seconds
// );
}

60
utils/oss.js Normal file
View File

@ -0,0 +1,60 @@
/*
* @Author: ckycjwds 1240973496@qq.com
* @Date: 2023-02-16 10:54:13
* @LastEditors: ckycjwds 1240973496@qq.com
* @LastEditTime: 2023-02-16 11:30:12
* @FilePath: \aiguo_erp_vue\src\utils\oss.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import { get_oss_sign_aliyun } from '@/api/user';
const base={
// oss上传地址
ossDv: "http://XXXXXXXX",
ossPr: "http://xXXXXXXX"
}
const isDev = process.env.NODE_ENV === 'development'
const OSSConfig = {
uploadHost: isDev ? base.ossDv : base.ossPr, //OSS上传地址
type: "scs",
ossParams: {
region: "oss-cn-beijing",
success_action_status: "200", // 默认200
bucket: "ddzb-wx"
},
// 获取临时stsToken
_initData() {
get_oss_sign_aliyun().then(res=>{
const { accessKeyId, accessKeySecret, securityToken } = res.datas;
this.ossParams.accessKeyId = res.datas.accessid;
this.ossParams.accessKeySecret = res.datas.secret;
this.ossParams.securityToken = securityToken;
})
.catch(err => {
console.log(err)
});
// http
// .get(api.getOssToken)
// .then(res => {
// const { accessKeyId, accessKeySecret, securityToken } = res;
// this.ossParams.accessKeyId = accessKeyId;
// this.ossParams.accessKeySecret = accessKeySecret;
// this.ossParams.securityToken = securityToken;
// })
// .catch(err => {
// console.log(err)
// });
}
};
OSSConfig._initData();
export { OSSConfig };
// oss地址
// export const ossUrl = 'http://aiguovip2020.oss-cn-shenzhen.aliyuncs.com'
export const ossUrl = 'http://erp-temporary-file.oss-cn-hangzhou.aliyuncs.com/'

60
utils/public.js Normal file
View File

@ -0,0 +1,60 @@
/**
1. 函数节流分页加载点击事件使用
2. @param fn
3. @param interval
4. @returns {Function}
5. @constructor
*/
export const Throttle = (fn, t) => {
let last;
let timer;
let interval = t || 500;
return function() {
let args = arguments;
let now = +new Date();
//等待执行
if (last && now - last < interval) {
clearTimeout(timer);
timer = setTimeout(() => {
// fn.apply(this, args); //非立即执行则在wait毫秒内的结束处执行快速点击N下的时候不需要触发函数
last = now;
}, interval);
} else {
fn.apply(this, args);//立即执行则在wait毫秒内开始时执行
last = now;
}
}
}
/**
* 函数防抖 搜索框搜索使用
* @param fn
* @param delay
* @returns {Function}
* @constructor
*/
export const Debounce = (fn, t) => {
let delay = t || 500;
let timer;
return function() {
let args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
timer = null;
fn.apply(this, args);
}, delay);
}
};
export const Debounce2 = (fn, t) => {
let time = t || 500;
let timeout = null;
return function() {
clearTimeout(timeout)
timeout = setTimeout(() => {
fn.apply(this, arguments);
}, time);
}
};

27
utils/remScale.js Normal file
View File

@ -0,0 +1,27 @@
// // 获取屏幕宽度
// var screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
// console.log(screenWidth);
// // 设置基础字体大小,可以根据需要调整
// var baseFontSize = 16;
// // 根据屏幕宽度计算根元素的字体大小
// var calculatedFontSize = screenWidth / 1920 * baseFontSize;
// // 375是设计稿的宽度可以根据实际情况调整
// // 设置根元素的字体大小
// console.log(calculatedFontSize,"calculatedFontSize");
// (function (doc, win) {
// var docEl = doc.documentElement,
// resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
// recalc = function () {
// var clientWidth = docEl.clientWidth;
// if (!clientWidth) return;
// if(clientWidth>=720){
// docEl.style.fontSize = calculatedFontSize+"px";
// }else{
// docEl.style.fontSize = 16 * (clientWidth / 720) + 'px';
// }
// };
// if (!doc.addEventListener) return;
// win.addEventListener(resizeEvt, recalc, false); //绑定事件
// doc.addEventListener('DOMContentLoaded', recalc, false);
// })(document, window);

196
utils/request _java.js Normal file
View File

@ -0,0 +1,196 @@
/*
* @Author: your name
* @Date: 2020-09-08 18:06:28
* @LastEditTime: 2023-03-06 14:54:24
* @LastEditors: ckycjwds 1240973496@qq.com
* @Description: In User Settings Edit
* @FilePath: \aiguo_erp_vue\src\utils\request.js
*/
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// import cancelClass from './cancelToken'
const VUE_APP_BASE_API='http://ag2.xtkj99.com:20248'
const service = axios.create({
baseURL: VUE_APP_BASE_API,
timeout: 1000 * 60 * 2 // 接口超时
})
const pendingAjax = []
const fastClickMsg = '数据请求中,请稍后'
const CancelToken = axios.CancelToken;
let lastcancel=null;
const removePendingAjax = (config, type, c) => {
if (type.type == 1) {
if (config.data) {
config.data = JSON.stringify(config.data)
}
}
let url = config.url
if (!!config.data && config.data != '{}') {
url = config.url + '_' + config.data
}
// 数据请求中白名单
const whitelist = ['get_class_account_list', 'cate_brand_list_all', 'ai_model_v2', 'res_advanced_search', 'qrcode', 'account_class_list', 'search_accessories', 'zz_new_status', 'get_unread_msg', 'third_party_no', 'get_ws_auth_code', 'get_drafts_box', 'manual_pull_datas', 'get_unopened_module', 'sales_performance_detail', 'goal_warehouse', 'chx_product_details', 'get_oss_sign_aliyun']
const index = pendingAjax.findIndex(i => i === url)
const white = whitelist.some(res => {
if (url.indexOf(res) != -1) {
return true
}
})
if (white) { // 白名单内的接口可以重复请求
pendingAjax.splice(index, 1)
} else {
if (index > -1) {
c ? c(fastClickMsg + url) : pendingAjax.splice(index, 1)
} else {
c && pendingAjax.push(url)
}
}
}
// 请求拦截
service.interceptors.request.use(
config => {
// if (navigator.onLine) { //检测网络是否正常
if (store.getters.token) {
config.headers['token'] = localStorage.getItem('token')
}
if(!lastcancel){
lastcancel= new CancelToken(c => {
const copyconfig = JSON.parse(JSON.stringify(config))
removePendingAjax(copyconfig, { type: 1 }, c)
});
}
config.cancelToken=lastcancel;
// config.cancelToken = new CancelToken(c => {
// const copyconfig = JSON.parse(JSON.stringify(config))
// removePendingAjax(copyconfig, { type: 1 }, c)
// })
return config
// }else{
// Message({
// duration:4000,
// message: '请检查网络状态',
// type: 'warning',
// showClose:true,
// })
// return
// }
},
error => {
return Promise.reject(error)
}
)
// 响应拦截
service.interceptors.response.use(
async response => {
const res = response.data
const copyconfig = JSON.parse(JSON.stringify(response.config))
copyconfig.url = response.config.url.replace(copyconfig.baseURL, '')
if (typeof (copyconfig.data) === undefined || copyconfig.data == {} || copyconfig.data == '' || typeof (copyconfig.data) === 'object') {
copyconfig.data = ''
}
removePendingAjax(copyconfig, { type: 2 })
lastcancel=null;
if (res.errcode == 1012) {
return res
} else if (res.errcode == 0 && res.msg != '' && res.msg != '成功' && res.msg != '获取成功') {
Message({
duration: 4000,
message: res.msg,
type: 'success',
showClose: true
})
return res
} else if (res.errcode == 105) { // 数据请求过快
Message({
duration: 1000,
message: res.msg,
type: 'warning',
showClose: true
})
} else if (res.errcode == 1002) {
// Message({
// duration:4000,
// message: res.msg,
// type: 'warning',
// showClose:true,
// })
// await store.dispatch('user/resetToken')
// 账号多地登陆 清空token 跳转到登陆页面
await store.dispatch('user/resetToken').then(() => {
location.reload()
})
/* 这里是判断识别sn的接口地址 如果为真 就把content返回*/
} else if (res.errcode == 50086) {
return res
} else if (res.errcode != 0) {
Message({
duration: 4000,
message: res.msg,
type: 'warning',
showClose: true
})
return res
/* 这里是判断识别sn的接口地址 如果为真 就把content返回*/
} else if (response.config.url.indexOf('https://apiv1.aiguovip.com/api/query/identify_sn_imei') > -1) {
return res.content
} else {
return res
}
},
error => {
console.log(error.message,"requesterror");
if (error.message.indexOf('数据请求中') != -1) {
Message({
duration: 1000,
showClose: true,
message: '数据请求中,请稍后...',
type: 'warning'
})
} else if (error.message.indexOf('timeout') != -1) {
const copyconfig = JSON.parse(JSON.stringify(error.config))
copyconfig.url = error.config.url.replace(copyconfig.baseURL, '')
if (typeof (copyconfig.data) === undefined || copyconfig.data == {} || copyconfig.data == '' || typeof (copyconfig.data) === 'object') {
copyconfig.data = ''
}
removePendingAjax(copyconfig, { type: 2 })
Message({
duration: 4000,
showClose: true,
message: '接口请求超时',
type: 'error'
})
} else {
// console.log(Object.getOwnPropertyNames(error));
// console.log(error.stack);
// console.log(error.message);
let copyconfig=null;
if(error?.response?.config){
copyconfig = JSON.parse(JSON.stringify(error.response.config))
copyconfig.url = error.response.config.url.replace(copyconfig.baseURL, '')
}
if(!copyconfig||typeof (copyconfig.data) === undefined || copyconfig.data == {} || copyconfig.data == '' || typeof (copyconfig.data) === 'object') {
copyconfig.data = ''
}
removePendingAjax(copyconfig, { type: 2 })
Message({
duration: 4000,
showClose: true,
message: '接口请求超时',
type: 'error'
})
}
// return Promise.reject(error.response.data)
// return Promise.reject(error)
return error
}
)
export default service

View File

@ -9,9 +9,9 @@
import axios from 'axios'
import { MessageBox, Message } from 'element-ui';
// import cancelClass from './cancelToken'
const service = axios.create({
baseURL: process?.env?.VUE_APP_BASE_API??"http://dev-erp-api.xtkj99.com:7890",
baseURL: window?.VUE_APP_BASE_API?window.VUE_APP_BASE_API:"http://dev-erp-api.xtkj99.com:7890", // api 的 base_url
timeout: 1000 * 60 * 2 // 接口超时
})
@ -56,7 +56,7 @@ service.interceptors.request.use(
// if (navigator.onLine) { //检测网络是否正常
let token=localStorage.getItem("token");
if (token) {
config.headers['token'] = localStorage.getItem('token')
config.headers['token'] = token;
}
if(!lastcancel){
lastcancel= new CancelToken(c => {
@ -113,8 +113,17 @@ service.interceptors.response.use(
showClose: true
})
} else if (res.errcode == 1002) {
// Message({
// duration:4000,
// message: res.msg,
// type: 'warning',
// showClose:true,
// })
// await store.dispatch('user/resetToken')
// 账号多地登陆 清空token 跳转到登陆页面
localStorage.clear();
location.reload();
sessionStorage.clear();
location.reload()
/* 这里是判断识别sn的接口地址 如果为真 就把content返回*/
} else if (res.errcode == 50086) {
return res
@ -182,4 +191,4 @@ service.interceptors.response.use(
}
)
export default service
export default service;

29
utils/ruoyi.js Normal file
View File

@ -0,0 +1,29 @@
// 数据合并
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];
}
}
// 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;
};

48
utils/screen.js Normal file
View File

@ -0,0 +1,48 @@
/*
* @Author: your name
* @Date: 2021-04-06 11:41:52
* @LastEditTime: 2021-04-06 11:41:59
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \aiguo_erp_vue\src\utils\screen.js
*/
//滚动条在Y轴上的滚动距离
export function getScrollTop(){
var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
if(document.body){
bodyScrollTop = document.body.scrollTop;
}
if(document.documentElement){
documentScrollTop = document.documentElement.scrollTop;
}
scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
return scrollTop;
}
//文档的总高度
export function getScrollHeight(){
var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
if(document.body){
bodyScrollHeight = document.body.scrollHeight;
}
if(document.documentElement){
documentScrollHeight = document.documentElement.scrollHeight;
}
scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
return scrollHeight;
}
//浏览器视口的高度
export function getWindowHeight(){
var windowHeight = 0;
if(document.compatMode == "CSS1Compat"){
windowHeight = document.documentElement.clientHeight;
}else{
windowHeight = document.body.clientHeight;
}
return windowHeight;
}

14
utils/strlen.js Normal file
View File

@ -0,0 +1,14 @@
// 计算文本内容字符的长度
export default function strlen(str) {
var len = 0;
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
//单字节加1
if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
len++;
} else {
len += 2;
}
}
return len;
}

93
utils/tablescroll.js Normal file
View File

@ -0,0 +1,93 @@
import Vue from 'vue';
// 自定义table水平滚动条始终显示在可视区域
Vue.directive('perfectScrollbar', {
componentUpdated:function (el, binding,vnode) {
let trCount=vnode.context.tableData.length;// tr的个数
fixTabScrollbar(el,null,trCount)
}
})
//自定义app滚动事件
Vue.directive('appScroll', {
bind: function(el, binding, vNode) {
let start = (e) =>{
fixTabScrollbar(null,el)
}
// 添加事件监听器
el.addEventListener("scroll", start);
}
})
//app滚动->定位table的水平滚动条
function fixTabScrollbar(tabEle,appEle,trCount) {
var tabEle=tabEle||document.getElementsByClassName('el-table')[0] // table 元素
var appEle=appEle||document.getElementById("app") // 滚动条所在容器
console.log(tabEle);
console.log(appEle);
if(!(tabEle&&appEle)) return;
var tabContainer=tabEle.parentNode; // table 的父级容器
let thead = tabEle.getElementsByClassName('el-table__header-wrapper')[0];
let tbody = tabEle.getElementsByClassName('el-table__body-wrapper')[0];
var trCount=trCount||tbody.getElementsByTagName("tr").length //tr的个数
console.log(trCount);
let trHeight=50.4 //tr的高度自己设置的,这里el-table-column需要设置为 show-overflow-tooltip不然换行会影响tr的高度 elementui这个框架不知道0.4哪里来的
let theadHeight=thead.clientHeight?thead.clientHeight:60; // 表头的高度60是默认的高度(自己设置的)
let tabHeight=theadHeight+trHeight*trCount+18 //table的高度 18是el-table水平滚动条的高度
let tabWinWidth=thead.clientWidth //table视口的宽度
let tabWidth=thead.getElementsByTagName('table')[0].offsetWidth;//table的宽度
let appHeight=appEle.offsetHeight- getOffsetTop(appEle) // 窗口的高度
let tabOffsetTop=getOffsetTop(tabContainer) //table 距离顶部距离
let appScrollTop=appEle.scrollTop // 容器向上滚动的距离
let bottom=tabOffsetTop+tabHeight-appScrollTop-appHeight+208;
// let bottom=4407;
console.log(tabContainer);
console.log(theadHeight);
console.log(tabHeight);
console.log(tabOffsetTop);
console.log(appScrollTop);
console.log(appHeight);
console.log(bottom);
if(bottom>0&&tabWidth>tabWinWidth){ //底部大于0并且table的宽度大于el-table视口的宽度-->显示滚动条,并隐藏自己的滚动条
let scrollBarEle=null
let childEle=null
tabEle.classList.add("hide-scrollBar") //隐藏tableC自己的滚动条
if(document.getElementById('perfectScrollbar-div')==null){
scrollBarEle = document.createElement('div');
scrollBarEle.id = 'perfectScrollbar-div';
childEle=document.createElement('p');
childEle.id = 'perfectScrollbar-child';
tabContainer.appendChild(scrollBarEle);
scrollBarEle.appendChild(childEle);
scrollBarEle.style.display="block";
childEle.style.width=tabWidth+"px";
childEle.style.height="1px";
childEle.style.padding="0";
childEle.style.margin="0";
scrollBarEle.style.position="absolute";
scrollBarEle.style.overflowX="auto";
scrollBarEle.style.left="0px";
scrollBarEle.style.right="0px";
scrollBarEle.style.margin="auto";
}else{
scrollBarEle = document.getElementById('perfectScrollbar-div');
}
scrollBarEle.style.bottom=bottom+"px";
scrollBarEle.onscroll = function(){
let target=event.target;
let scrollLeft=target.scrollLeft
tbody.scrollLeft=scrollLeft;
}
}else{
tabEle.classList.remove("hide-scrollBar") //显示tableC自己的滚动条
var scrollBarEle=document.getElementById('perfectScrollbar-div');
if(scrollBarEle)scrollBarEle.parentNode.removeChild(scrollBarEle);
}
}
function getOffsetTop(obj) {
if (!!window.ActiveXObject || "ActiveXObject" in window) {
var y = obj.offsetTop;
while (obj = obj.offsetParent) y += obj.offsetTop;
return y;
}else{
return 0
}
}

20
utils/time.js Normal file
View File

@ -0,0 +1,20 @@
/*
* @Author: your name
* @Date: 2021-08-17 11:56:32
* @LastEditTime: 2021-08-18 15:31:56
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \aiguo_erp_vue\src\utils\time.js
*/
//毫秒
export function start_time() {
var now = new Date();
var year_4 = now.getFullYear();
var month = now.getMonth() + 1;
var date = now.getDate();
var time3 = Date.parse(`${year_4}-${month}-${date}`)
return time3
}

316
utils/timeData.js Normal file
View File

@ -0,0 +1,316 @@
import moment from "moment/moment";
// 获取当月第一天
export function getFirstDayOfMonth(date) {
date.setDate(1);
return this.timeFormat(date);
}
// 获取当天时间
export function getToday(type = 'YYYY-MM-DD HH:mm:ss') {
const obj = {
starttime: "",
endtime: "",
};
obj.starttime = moment(moment().startOf("day").valueOf()).format(
type
);
obj.endtime = moment(moment().valueOf()).format(type);
return obj;
}
/**
*
* @returns 今日的时间戳
*/
export function getTodayTime() {
// 获取今天的开始时间戳午夜00:00:00
const startOfToday = new Date();
startOfToday.setHours(0, 0, 0, 0);
const startOfTodayTimestamp = startOfToday.getTime();
// 获取今天的结束时间戳下一天的午夜前一秒即23:59:59
const endOfToday = new Date();
endOfToday.setHours(23, 59, 59, 999); // 设置时间为23:59:59.999
const endOfTodayTimestamp = endOfToday.getTime();
return {
startOfTodayTimestamp,
endOfTodayTimestamp,
};
}
// 获取当月时间
export function getCurrMonthDays() {
const obj = {
starttime: "",
endtime: "",
};
obj.starttime = moment(
moment().month(moment().month()).startOf("month").valueOf()
).format("YYYY-MM-DD HH:mm:ss");
obj.endtime = moment(
moment().month(moment().month()).endOf("month").valueOf()
).format("YYYY-MM-DD HH:mm:ss");
return obj;
}
// 获取当月时间
export function getCurrMonthDay() {
const obj = {
starttime: "",
endtime: "",
};
obj.starttime = moment().month(moment().month()).startOf("month").valueOf()
obj.endtime = moment().endOf('day').valueOf()
return obj;
}
// 获取昨日时间
export function getYesterday(type = "YYYY-MM-DD HH:mm:ss") {
const obj = {
starttime: "",
endtime: "",
};
obj.starttime = moment(
moment().add(-1, "days").startOf("day").valueOf()
).format(type);
obj.endtime = moment(moment().add(-1, "days").endOf("day").valueOf()).format(
type
);
return obj;
}
// 获取近一周时间
export function getlastweek() {
const obj = {
starttime: "",
endtime: "",
};
obj.starttime = moment(
moment().add(-7, "days").startOf("day").valueOf()
).format("YYYY-MM-DD HH:mm:ss");
obj.endtime = moment(moment().add(-1, "days").endOf("day").valueOf()).format(
"YYYY-MM-DD HH:mm:ss"
);
return obj;
}
// 获取上个月时间
export function getLastMonthDays() {
const obj = {
starttime: "",
endtime: "",
};
obj.starttime = moment(
moment()
.month(moment().month() - 1)
.startOf("month")
.valueOf()
).format("YYYY-MM-DD HH:mm:ss");
obj.endtime = moment(
moment()
.month(moment().month() - 1)
.endOf("month")
.valueOf()
).format("YYYY-MM-DD HH:mm:ss");
return obj;
}
// 时间戳转化为 YY-mm-dd hh-mm-ss格式
export function filterTime2(time) {
var date = new Date(time);
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? "0" + m : m;
var d = date.getDate();
d = d < 10 ? "0" + d : d;
var h = date.getHours();
h = h < 10 ? "0" + h : h;
var minute = date.getMinutes();
minute = minute < 10 ? "0" + minute : minute;
var s = date.getSeconds();
s = s < 10 ? "0" + s : s;
return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + s;
}
// 时间戳转化为 YY-mm-dd 格式
export function filterTimeYMD(time) {
var date = new Date(time);
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? "0" + m : m;
var d = date.getDate();
d = d < 10 ? "0" + d : d;
return y + "-" + m + "-" + d;
}
// 时间戳转化为 mm-dd 格式
export function filterTimeMD(time) {
var date = new Date(time);
var m = date.getMonth() + 1;
m = m < 10 ? "0" + m : m;
var d = date.getDate();
d = d < 10 ? "0" + d : d;
return m + "-" + d;
}
// 时间戳转化为 mm-dd 格式
export function filterTimeMDHM(time) {
var date = new Date(time);
var m = date.getMonth() + 1;
m = m < 10 ? "0" + m : m;
var d = date.getDate();
d = d < 10 ? "0" + d : d;
var h = date.getHours();
h = h < 10 ? "0" + h : h;
var minute = date.getMinutes();
minute = minute < 10 ? "0" + minute : minute;
return m + "-" + d + " " + h + ":" + minute;
}
// 获取特定天数
export function filterTime1(time) {
var date = new Date(time);
var d = date.getDate();
d = d < 10 ? "0" + d : d;
return d;
}
// 时间戳转化为 YY-mm-dd格式
export function filterTime3(time) {
var date = new Date(time);
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? "0" + m : m;
var d = date.getDate();
d = d < 10 ? "0" + d : d;
return y + "-" + m + "-" + d;
}
// 时间戳转化为 YY-mm格式
export function filterTime4(time) {
var date = new Date(time);
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? "0" + m : m;
return y + "-" + m;
}
// 根据每月的时间戳获取最后一天的时间戳
export function filterTime5(time) {
const now = new Date(time); // 当前日期
// console.log(now)
const nowMonth = now.getMonth(); // 当前月
const nowYear = now.getFullYear(); // 当前年
// this.tmieformat()
// console.log(nowMonth + 1)
const monthEndDate = new Date(nowYear, nowMonth + 1, 0, 23, 59, 59);
const c = Date.parse(monthEndDate);
return c;
}
// 返回小时
export function filterTimeHH(time) {
var date = new Date(time);
var h = date.getHours();
h = h < 10 ? "0" + h : h;
return h;
}
// 返回月天小时
export function filterTimeMDHS(time) {
var date = new Date(time);
var m = date.getMonth() + 1;
m = m < 10 ? "0" + m : m;
var d = date.getDate();
d = d < 10 ? "0" + d : d;
var h = date.getHours();
h = h < 10 ? "0" + h : h;
return m + "月" + d + "日" + h;
}
// 复杂数组对象去重
export function uniqueArray(array) {
return array.reduce((accumulator, currentValue) => {
const stringified = JSON.stringify(currentValue);
if (!accumulator.some((item) => JSON.stringify(item) === stringified)) {
accumulator.push(currentValue);
}
return accumulator;
}, []);
}
// 判断当月有多少天
export function getDaysInCurrentMonth() {
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth() + 1;
const nextMonthFirstDay = new Date(year, month, 1);
const lastDay = new Date(nextMonthFirstDay - 1);
return lastDay.getDate();
}
export function getnewdate(dataStr, pattern = "YYYY-MM-DD HH:mm:ss") {
if (dataStr) {
var date = new Date(dataStr / 1);
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? "0" + m : m;
var d = date.getDate();
d = d < 10 ? "0" + d : d;
var h = date.getHours();
h = h < 10 ? "0" + h : h;
var minute = date.getMinutes();
minute = minute < 10 ? "0" + minute : minute;
var s = date.getSeconds();
s = s < 10 ? "0" + s : s;
return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + s;
} else {
return "";
}
}
/**
*
* @returns 当前日期,格式为"yyyy-mm-dd"
*/
export function getCurrentDate() {
var today = new Date();
var dd = String(today.getDate()).padStart(2, "0");
var mm = String(today.getMonth() + 1).padStart(2, "0"); // 注意月份是从0开始的所以需要+1
var yyyy = today.getFullYear();
return yyyy + "-" + mm + "-" + dd;
}
/**
* @param {String} time 'yyyy-mm-dd'
* @returns 'yyyy-mm-dd'转为时间戳
*/
export function dateToTimestamp(time) {
if (time) {
var date = new Date(time);
return date.getTime();
}
}
/**
* @param {*} dateStr
* @returns '传入日期的最后一秒时间戳'
*/
export function getLastSecondTimestamp(dateStr) {
// 创建一个Date对象
var date = new Date(dateStr);
// 设置时间为当天的最后一秒
date.setHours(23, 59, 59);
// 返回时间戳
return date.getTime();
}
/**
* @returns '上个月的时间戳'
*/
export function getLastMounthTime() {
// 获取当前日期
const now = new Date();
// 设置日期为上个月的第一天
const startOfPreviousMonth = new Date(
now.getFullYear(),
now.getMonth() - 1,
1
);
// 设置日期为上个月的最后一天
const endOfPreviousMonth = new Date(now.getFullYear(), now.getMonth(), 0);
// 设置时间为当天的最后一秒
endOfPreviousMonth.setHours(23, 59, 59, 999);
// 获取时间戳
const startOfLastMonth = startOfPreviousMonth.getTime();
const endOfLastMonth = endOfPreviousMonth.getTime();
return {
startOfLastMonth,
endOfLastMonth,
};
}

20
utils/validate.js Normal file
View File

@ -0,0 +1,20 @@
/**
* Created by PanJiaChen on 16/11/18.
*/
/**
* @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
}

22
utils/versionUpdate.js Normal file
View File

@ -0,0 +1,22 @@
import axios from 'axios'
const isNewVersion = () => {
let url = `//${window.location.host}/static/version.json?t=${new Date().getTime()}`;
axios.get(url).then(res => {
if (res.status === 200) {
let vueVersion = res.data.version;
let localVueVersion = localStorage.getItem('vueVersion');
if (localVueVersion && localVueVersion != vueVersion) {
localStorage.setItem('vueVersion', vueVersion);
window.location.reload();
return;
} else {
localStorage.setItem('vueVersion', vueVersion);
}
}
});
}
export default {
isNewVersion
}