登录封装完成

This commit is contained in:
2022-05-09 10:03:33 +08:00
parent 5bae62d34d
commit e7a130533d
19 changed files with 604 additions and 70 deletions
+17
View File
@@ -0,0 +1,17 @@
import Taro from "@tarojs/taro";
/**
* 设置 客户 本地存储
* @param {Object} clientInfo
*/
export const setClient = (clientInfo) => {
Taro.setStorageSync('client', clientInfo)
}
/**
* 返回 客户 本地存储
*/
export const getClient = () => {
Taro.getStorageSync('client') || null
}
+135
View File
@@ -0,0 +1,135 @@
/**
* 移除井号
* @param {String} val code 编码
* @returns
*/
export const formatRemoveHashTag = (val = "") => {
// console.log('移除标签',val,val.endsWith("#"));
return val.endsWith("#") ? val.replace("#", "") : val;
};
/**
* 格式化编码+名称显示方式
* @param {String} code 编码
* @param {String} name 名称
* @param {*} mode 模式 both:code + 名称 name: 仅显示名称
* @returns
*/
export const formatHashTag = (code = "", name = "", mode = "both") => {
if (mode == 'both') {
return `${formatRemoveHashTag(code)}# ${name}`
} else if (mode == 'name') {
return `${name}`
}
}
const Digit = 10 * 10
/**
* 重量 进退位 单位
*/
export const weightDigit = 1000
/**
* 除以
* @param {*} val
* @param {*} digit
* @returns
*/
export const formatPriceDiv = (val, digit = Digit) => {
return strip(Number(val / digit)) || 0
}
/**
* 乘以
* @param {*} val
* @param {*} digit
* @returns
*/
export const formatPriceMul = (val, digit = Digit) => {
return strip(Number(val * digit)) || 0
}
/**
* 格式化重量单位 (乘以)
* @param {Number} val
* @returns
*/
export const formatWeightMul = (val, digit = weightDigit) => {
return strip(Number(val * digit)) || 0
}
/**
* 格式化重量单位 (除以)
* @param {*} val
*/
export const formatWeightDiv = (val, digit = weightDigit) => {
return strip(Number(val / digit)) || 0
}
export const formatDateTime = (val, fmt = "YYYY-MM-DD HH:mm:ss") => {
if (val) {
let time = new Date(val)
let Y = time.getFullYear()
let M = time.getMonth() + 1
let d = time.getDate()
let h = time.getHours()
let m = time.getMinutes()
let s = time.getSeconds()
fmt = fmt.replace('YYYY', Y).replace('MM', M.toString().padStart(2, '0')).replace('DD', d.toString().padStart(2, '0')).replace('HH', h.toString().padStart(2, '0')).replace('mm', m.toString().padStart(2, '0')).replace('ss', s.toString().padStart(2, '0'))
// fmt = fmt.replace('MM', M)
// fmt = fmt.replace('DD', d)
// fmt = fmt.replace('HH', h)
// fmt = fmt.replace('mm', m)
// fmt = fmt.replace('ss', s)
return fmt
} else {
return val
}
}
/**
* 精度
* @param {*} num
* @param {*} precision
* @returns
*/
export const strip = (num, precision = 12) => {
return +parseFloat(num.toPrecision(precision));
}
/**
* 转换金额单位
* @param {*} num 金额 / 数值
* @param {*} digit 转换单位
* @returns
*/
export const formatMillionYuan = (num, digit = 10000) => {
return num / digit > 1 ? { num: toDecimal2(num / digit), million: true } : { num, million: false }
}
/**
* 数值保留两位小数
* @param {*} x
* @returns
*/
export const toDecimal2 = (x) => {
var f = parseFloat(x);
if (isNaN(f)) {
return 0;
}
f = f + "";
let index = f.lastIndexOf('.');
if (index >= 0) {
let decimal = f.substring(index + 1);
if (decimal.length == 1) {
f = f.substring(0, index + 1) + decimal + "0";
} else {
f = f.substring(0, index + 1) + decimal.substring(0, 2);
}
}
return f;
}
+34
View File
@@ -0,0 +1,34 @@
import Taro from "@tarojs/taro";
/**
* 设置 系统 本地存储
* @param {Object} systemInfo
*/
export const setSystem = (systemInfo) => {
Taro.setStorageSync('system', JSON.stringify(systemInfo))
}
/**
* 返回 系统 本地存储
*/
export const getSystem = () => {
const result = Taro.getStorageSync('system')
return result ? JSON.parse(result) : null
}
/**
* 设置 小程序 本地存储
* @param {Object} systemInfo
*/
export const setAccountInfo = (systemInfo) => {
Taro.setStorageSync('accountInfo', JSON.stringify(systemInfo))
}
/**
* 返回 系统 本地存储
*/
export const getAccountInfo = () => {
const result = Taro.getStorageSync('accountInfo')
return result ? JSON.parse(result) : null
}
+150
View File
@@ -0,0 +1,150 @@
import Taro from '@tarojs/taro';
import { GET_UPLOAD_SIGN, CDN_UPLOAD_IMG, UPLOAD_CDN_URL } from './constant'
import { GetSignApi } from '@/api/cdn'
const { fetchData: GetSign, success, data: resData, msg, code } = GetSignApi()
// 上传图片 获取auth,Policy
/*
scene 场景值,区分上传文件的根路径
type 类型值,区分上传业务bucket
*/
const getSecret = (scene, type) => {
return new Promise(async (resolve, reject) => {
const SAVE_PATH = `/${scene}/{filemd5}{day}{hour}{min}{sec}{.suffix}`;
let params = {
'method': 'post',
'save_key': SAVE_PATH
}
// 获取签名
await GetSign(params)
if (success.value) {
// console.log('返回签名',resData.value);
resolve(resData.value)
} else {
reject({
code: code.value || '9999',
msg: msg.value
});
}
})
}
const getFileType = (name) => {
if (!name) return false;
var imgType = ["gif", "jpeg", "jpg", "bmp", "png"];
var videoType = ["avi", "wmv", "mkv", "mp4", "mov", "rm", "3gp", "flv", "mpg", "rmvb", "quicktime"];
if (RegExp("\.?(" + imgType.join("|") + ")$", "i").test(name.toLowerCase())) {
return 'image';
} else if (RegExp("\.(" + videoType.join("|") + ")$", "i").test(name.toLowerCase())) {
return 'video';
} else {
return false;
}
}
const upYunbucket = (type) => {
var bucket = ""
switch (type) {
case "product":
bucket = "testzzfzyc"
break;
}
return bucket
}
/**
*
* @param {*} file 传入文件
* @param {String} secene 传入 'product'
* @param {String} type 传入 'product'
* @returns
*/
const uploadCDNImg = (file, secene, type) => {
// var file = event.target.files[0];
// var filetype = file.type
let filetype = file.tempFilePath
if (!getFileType(filetype)) {
Taro.showToast({
title: "上传文件类型错误",
icon: "none",
duration: 3800
})
return false
}
return new Promise((resolve, reject, race) => {
getSecret(secene, type)
.then(result => {
console.log('bucket', result.bucket);
var formdata = {
'authorization': result.authorization,
'policy': result.policy,
// "file": file.tempFilePath,
}
const uploadTask = Taro.uploadFile({
url: `${UPLOAD_CDN_URL}${result.bucket}`,
formData: formdata,
filePath: file.tempFilePath,
name: 'file',
success: res => {
resolve(JSON.parse(`${res.data}`))
},
fail: err => {
console.log(err)
reject(err)
}
})
uploadTask.progress(res => {
console.log('上传进度', res.progress);
if (res.progress < 100) {
Taro.showLoading({
title: '上传中...'
})
} else {
Taro.hideLoading()
}
})
})
.catch(result => {
reject(result)
Taro.showToast({
title: "获取密钥失败!",
icon: "none",
duration: 3800
})
})
})
}
const taroChooseImg = () => {
Taro.chooseImage({
count: 1,
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: (res) => {
console.log('res:', res)
Taro.chooseMessageFile({
count: 1,
})
},
fail: (err) => {
console.log('图片选择失败:', err)
}
})
}
export default uploadCDNImg
+36
View File
@@ -0,0 +1,36 @@
import Taro from "@tarojs/taro";
import { useStore } from "vuex";
import { computed } from "@vue/runtime-core";
/**
*
* @param {String} token
*/
export const setToken = (token) => {
Taro.setStorageSync('token', token)
}
/**
*
* @param {Object} userinfo
*/
export const setUserInfo = (userinfo) => {
Taro.setStorageSync('userInfo', userinfo)
}
/**
* 检查登录
*/
export const checkLogin = () => {
const store = useStore()
const token = computed(() => store.state.token)
console.log('checklogin token', token);
// 本地调试屏蔽
if (token == '') {
Taro.redirectTo({
url: '/pages/login/index',
})
}
}
+94
View File
@@ -0,0 +1,94 @@
/**
* 防抖
* @param {*} fn
* @param {*} delay
* @returns
*/
export const debounce = (fn, delay) => {
let timer = null;
return (...param) => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn(...param);
}, delay);
};
}
/**
* 节流
* @param {*} fn
* @param {*} delay
* @returns
*/
export const throttle = (fn, delay) => {
let pre = 0;
return (...params) => {
let now = new Date().getTime();
console.log('相差:',now-pre)
if (now - pre > delay) {
fn(...params);
pre = now;
}
};
}
/**
* 批量过滤对象值为空的属性
* @param {Object} val 需要过滤的对象
* @param {Array} arr 排除过滤的属性
* @returns
*/
export const getFilterData = (val = {}, arr = []) => {
let res = {}
for(let key in val) {
if(val[key]!=undefined&&val[key]!=null&&(!arr.includes(key))){
if(val[key] instanceof Number){
console.log("+++",val[key]);
if(!isNaN(val[key])) {
res[key] = val[key]
}
}else{
res[key] = val[key]
}
}
}
return res
}
/**
* 对象深拷贝
* @param {*} object
* @returns
*/
export const copyObject = (object)=>{
if(object.constructor==Object){
let keys = Object.keys(object);
let newObject = {};
keys.map(key=>{
newObject[key]= copyObject(object[key]);
})
return newObject;
}else if(object.constructor==Array){
return object.map(item=>{
return copyObject(item);
})
}else{
return object;
}
}
/**
*
* @param {*} suffix
* !w80
!w100
!w160
!w200
!w400
!w800
!wh400
!w600
*/
export const screenshot = (url, suffix="!w200")=>{
return url+suffix;
}